Flow Controls: If-Else Branching
Flow Controls: If-Else Branching
Flow Controls: If-Else Branching
switch Statements
A way to simulate the use of multiple if statements is with the switch statement.
Take a look at the following if-else code, and notice how confusing it can be to
have nested if tests, even just a few levels deep:
int x = 3;
if(x == 1) {
System.out.println("x equals 1");
}
else if(x == 2) {
System.out.println("x equals 2");
}
else if(x == 3) {
System.out.println("x equals 3");
}
else {
System.out.println("No idea what x is");
}
Now let's see the same functionality represented in a switch construct:
int x = 3;
switch (x) {
case 1:
System.out.println("x is equal to 1");
break;
case 2:
System.out.println("x is equal to 2");
break;
case 3:
System.out.println("x is equal to 3");
break;
default:
System.out.println("Still no idea what x is");
}
Note: The reason this switch statement emulates the nested ifs listed earlier is
because of the break statements that were placed inside of the switch. In general,
Legal Expressions for switch and case
The general form of the switch statement is:
switch (expression) {
case constant1: code block
case constant2: code block
default: code block
}
Note:-
A switch's expression must evaluate to a char, byte, short, int
Only convertible int values, strings or enum variables are permitted.
switch (2L), switch (2d), switch (2.0) . Not permitted
A case constant must evaluate to the same type as the switch expression can use
switch (2) { // compiler error.
case "hi":
}
switch (‘A’) { // fine char may convert into int implicitly.
case 6:
}
The case constant must be a compile time constant! Since the case argument has to be resolved at
compile time, that means you can use only a constant or final variable that is assigned a literal value. It is
not enough to be final, it must be a compile time constant. For example:
final int a = 1;
final int b;
b = 2;
int x = 0;
switch (x) {
case a: // ok
case b: // compiler error
•Also, the switch can only check for equality. This means that the other relational
operators such as greater than are rendered unusable in a case.
switch (x==2)// error switch (x=2) //fine.
String s = "xyz";
switch (s.length())// fine it return a value that compatible with an int.
byte g = 2;
switch(g) {
case 23:
case 128:// compiler error possible loss of precision.
}
It's also illegal to have more than one case label using the same value.
int temp = 90;
switch(temp) {
case 80 : System.out.println("80");
case 80 : System.out.println("80"); // won't compile!
case 90 : System.out.println("90");
default : System.out.println("default");
}