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.

Active1 year, 3 months ago

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.

ManoDestra
4,9535 gold badges15 silver badges40 bronze badges
randeepsprandeepsp

Java Switch Multiple Case

1,4788 gold badges25 silver badges38 bronze badges

13 Answers

Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

cdeszaq
23.1k23 gold badges107 silver badges161 bronze badges
nickdosnickdos
7,3685 gold badges24 silver badges45 bronze badges

Learn 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...

cHaoUsingcHao
70.9k15 gold badges121 silver badges158 bronze badges

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).
Community
SuragchSuragch
239k139 gold badges793 silver badges875 bronze badges
Sample Program In Java Using Switch Case

To reduce cyclomatic complexity use a map:

or polymorphism

emoryemory
9,4341 gold badge24 silver badges51 bronze badges

Just 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 :

m.piuntim.piunti

Java does not support Switch-case with String. I guess this link can help you. :)

Community
Sunmit GirmeSunmit Girme
3433 gold badges11 silver badges28 bronze badges

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 unknown
30k10 gold badges64 silver badges112 bronze badges

We can apply Switch just on data type compatible int :short,Shor,byte,Byte,int,Integer,char,Character or enum type.

omaromar

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.

Desta Haileselassie HagosDesta Haileselassie Hagos
10.9k2 gold badges31 silver badges42 bronze badges
YashYash
latifalatifa
Conete CristianConete Cristian
TriquiTriqui

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
publicstaticvoidmain(String[] args)
intday = 5;
switch(day) {
dayString = 'Monday';
case2:
break;
dayString = 'Wednesday';
case4:
break;
dayString = 'Friday';
case6:
break;
dayString = 'Sunday';
default:
break;
System.out.println(dayString);
}

Output:

Program

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
publicstaticvoidmain(String[] args)
intday = 2;
String dayString;
switch(day) {
dayString = 'Monday';
case2:
break;
dayString = 'Wednesday';
case4:
break;
dayString = 'Friday';
case6:
break;
dayString = 'Sunday';
default:
}
switch(day) {
case2:
case4:
dayType = 'Weekday';
case6:
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
publicstaticvoidmain(String[] args)
String Branch = 'CSE';
case1:
System.out.println('elective courses : Advance english, Algebra');
case2:
{
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.


Prime Numbers Sample Program In Java

Recommended Posts: