O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required