LEARN MATE Request book Contact us quizes Books Home
if...else statement
Java supports the usual logical conditions from mathematics: Less than: a < b Less than or equal to: a <=b Greater than: a> b: if (condition) { // block of code to be executed if the condition is true } Java has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

if (20 > 18) { System.out.println("20 is greater than 18"); } In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day". int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 20) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening." There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.; if (time < 18) { printf("Good day."); } else { printf("Good evening."); } // Outputs "Good evening." In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good evening". However, if the time was 14, our program would print "Good day." int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 20) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening."; }