If/Else
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"); }
Switch/Case and Breaks
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 ...
Get Java Garage now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.