Sample Program In Java Using Switch Case
The program takes the value of both the numbers (entered by user) and then user is asked to enter the operation (+, -, * and /), based on the input program performs the selected operation on the entered numbers using switch case. If you are new to java, refer this Java tutorial to start learning java programming from basics. Java Example Program to Calculate Electricity Bill String Program using compareToIgnoreCase(String str) method Java Example Program to find whether a matrix Zero. In this program, you'll learn to make a simple calculator using switch.case in Java. This calculator would be able to add, subtract, multiply and divide two numbers. Example: Simple Calculator using switch.
I need to change the following if
's to a switch
-case
while checking for a String
, to improve the cyclomatic complexity.
But I am not sure what value I'm going to get.
ManoDestraJava Switch Multiple Case
13 Answers
Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.
cdeszaqLearn to use else
.
Since value
will never be equal to two unequal strings at once, there are only 5 possible outcomes -- one for each value you care about, plus one for 'none of the above'. But because your code doesn't eliminate the tests that can't pass, it has 16 'possible' paths (2 ^ the number of tests), of which most will never be followed.
With else
, the only paths that exist are the 5 that can actually happen.
Or start using JDK 7, which includes the ability to use strings in a switch
statement. Course, Java will just compile the switch
into an if
/else
like construct anyway...
Everybody is using at least Java 7 now, right? Here is the answer to the original problem:
Notes
- The case statements are equivalent to using
String.equals
. - As usual, String matching is case sensitive.
- According to the docs, this is generally faster than using chained
if
-else
statements (as in cHao's answer).
To reduce cyclomatic complexity use a map:
or polymorphism
emoryemoryJust to make concrete emory's answer, the executable code is the following :
where user is a POJO, and then
finally the called method is somewhere :
Java does not support Switch-case with String. I guess this link can help you. :)
Here is a possible pre-1.7 way, which I can't recommend:
Maybe you could work with such a trick in a generated code. Else I can't recommend it. Not so much that the possibility of a hash collision makes me worry, but if something is mixed up (cut and paste), it is hard to find the error. 931605 is not a good documentation.
Take it just as proof of concept, as curiosity.
user unknownuser unknownWe can apply Switch just on data type compatible int :short,Shor,byte,Byte,int,Integer,char,Character or enum type.
Evaluating String
variables with a switch statement have been implemented in Java SE 7, and hence it only works in java 7. You can also have a look at how this new feature is implemented in JDK 7.
Not the answer you're looking for? Browse other questions tagged javastringswitch-statement or ask your own question.
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class and Wrapper classes.
Syntax of Switch-case :
Flow Diagram of Switch-case :
Some Important rules for switch statements :
- Duplicate case values are not allowed.
- The value for a case must be the same data type as the variable in the switch.
- The value for a case must be a constant or a literal.Variables are not allowed.
- The break statement is used inside the switch to terminate a statement sequence.
- The break statement is optional. If omitted, execution will continue on into the next case.
- The default statement is optional, and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of next case statement.
Examples:
Consider the following java program, it declares an int named day whose value represents a day(1-7). The code displays the name of the day, based on the value of day, using the switch statement.
// with primitive(int) data type public static void main(String[] args) int day = 5 ; switch (day) { dayString = 'Monday' ; case 2 : break ; dayString = 'Wednesday' ; case 4 : break ; dayString = 'Friday' ; case 6 : break ; dayString = 'Sunday' ; default : break ; System.out.println(dayString); } |
Output:
Omitting the break statement
As break statement is optional. If we omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For example, consider the updated version of above program, it also displays whether a day is a weekday or a weekend day.
Sample Program In Java Netbeans
// with multiple cases without break statements public static void main(String[] args) int day = 2 ; String dayString; switch (day) { dayString = 'Monday' ; case 2 : break ; dayString = 'Wednesday' ; case 4 : break ; dayString = 'Friday' ; case 6 : break ; dayString = 'Sunday' ; default : } switch (day) { case 2 : case 4 : dayType = 'Weekday' ; case 6 : dayType = 'Weekend' ; dayType = 'Invalid daytype' ; System.out.println(dayString + ' is a ' + dayType); } |
Output:
Nested Switch Case statements
We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. For example:
// nested switch case statement public static void main(String[] args) String Branch = 'CSE' ; case 1 : System.out.println( 'elective courses : Advance english, Algebra' ); case 2 : { case 'CCE' : System.out.println( 'elective courses : Machine Learning, Big Data' ); System.out.println( 'elective courses : Antenna Engineering' ); System.out.println( 'Elective courses : Optimization' ); } } |
Output:
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.