August 2004
Intermediate to advanced
480 pages
9h 41m
English
The if/else statement is used to execute code when a test condition is true.
if (x > 10) {
System.out.println("x is greater than 10");
} else {
System.out.println("x is less than 10");
}
The following code shows how to use a switch/case construct with a char. But any of the following primitive types are legal to test against: char, byte, short, or int.
switch (test) {
case 'A' :
System.out.print("Found X");
break; //Print 'X' if test = 'X'
case 'B' :
System.out.print("Found Y");
break; //Print 'Y' if test = 'Y'
default :
//This code runs if test does not equal 'X' or 'Y'
System.out.print("Found Z");
}
If neither break were there, and if test equaled 'X', the code would print XYZ. Java switch/case constructs ...
Read now
Unlock full access