The if statement has two forms: if-then and if-then-else. Before taking a look to how these two forms are used, make sure you understand the related terminology:

  • Operators, Variables and Literals can be used in building expressions, which compute to values
  • Expressions are the core components of statements which are ended with a semicolon: statement;
  • Statements may be grouped into blocks by using brackets. A block can also be empty, having no statements at all: { 0_to_N_statements }

You can use if statements with statements or blocks, although it’s always recommended to use blocks for legibility reasons.

The syntax of the if-then form is:

Example:

The syntax of the if-then-else form is:

Example:

Be careful of tricky questions in the exam that try to confuse you by using a wrong indentation that doesn’t help you to match every if with its corresponding else:

In the previous example, the else at line 5 corresponds to the if (true) statement at line 3 and not to the if (false) at line 2 (as it could be inferred from the intentional wrong indentation). The final output of this code is nothing: lines 3  to 7 are never reached.

Note that using false as the expression for if is allowed by the Java Language Specification (e.g. for debug purposes) and doesn’t generate an Unreachable code compiler error.


Leave a Reply