if and else keywords

Syntax

>>-if-(-Expression-)-Statement-+----------------+-><
                               '-else-Statement-'

Description
The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.

An if-then statement is executed by first evaluating an expression.

The else keyword enables you to provide a statement to execute if the test in an if statement is false. An if-then-else statement is executed by first evaluating an expression.

Dangling else problem
As in C and C++, the Java if statement has the so-called "dangling else problem," illustrated by this misleadingly formatted example:

if (door.isOpen())
        if (resident.isVisible())
                resident.greet("Hello!");
else door.bell.ring(); // A "dangling else"

The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement. However, the Java language, like C and C++ and many languages before them, decrees that an else clause belongs to the innermost if to which it might possibly belong.

Example
The following is an example of a simple if statement:

/*
 * If a equals five, we will print out the word Good;
 * otherwise nothing will be printed.
 */
if (a == 5)
    System.out.println ("Good"); 

The following is an extension of the above example with an else statement:

if (a == 5) 
    System.out.println ("Good");
else 
    System.out.println ("Not Good"); 

ngrelr.gif (548 bytes)
Syntax diagrams
Java types
boolean keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.