Witscale Test Center

5.2 Conditional statements: if, if-else and switch > 5.2.1 The if statement


5.2.1 The if statement

The if statement chooses the execution path based on a condition. This condition is in the form of boolean expression. The basic format of an if statement is as:

 

if(booleanExpression) {

   [Statements;]

}

 

The condition in booleanExpression must be evaluated to true or false. The curly brackets enclose the statements to be executed when the condition is true. The curly brackets are optional, if they are absent only the first statement after if() is executed when the condition is true. For example,

 

if(a<4)

 System.out.println(“a is less than 4”);

a = a + 6;

 

If a is indeed less than 4, the condition in if() is true. Since there are no curly brackets the first statement is executed and the message “a is less than 4” is printed. The second statement a = a + 6; is always executed whether or not the condition is true. To avoid confusion, you may enclose the statements of the if block with curly brackets, even if there is just one statement in the if block.