if statements

index
BASIC

There are two kinds of if statements--those with an else clause, and those without an else clause.

Without an else clause

An if statement tests a condition. If the condition is true, the following statement (typically, a block) is executed. If the condition is not true, the if statement does nothing. The syntax is:

if (condition) {
    statements
} 

For example,

if (x < 0) {
    x = 0;
} 

The above if statement resets x to zero if it has become negative.

The braces indicate a block of statements. If there is only one statement, the braces may be omitted; however, it is good style to always include the braces (reasons are given below).

With an else clause

An if-else statement tests a condition, and chooses one of two statements to execute. If the condition is true, the statement following the condition is executed. If the condition is not true, the statement following the else is executed. Both statements are typically blocks. The syntax is:

if (condition) {
    some statements
}
else {
    some other statements
}

For example,

if (x == 0) {
    System.out.println("x is zero");
}
else {
    System.out.println("x is not zero");
} 
STYLE
  1. If you leave out the braces around the "true part", the semicolon makes it look like the else is a separate statement. It is not. There is no such thing as an "else statement."
    if (x == 0)
        System.out.println("x is zero");
    else {
        System.out.println("x is not zero");
    } 
  2. If you leave out the braces, it is easy to make the following error:
    if (x < 0)
        System.out.println("x reset to zero");
        x = 0;
    System.out.println("x is now " + x); // always prints 0
    

    The indentation suggests that two statements are under control of the if statement, but in fact only the first one is.

    For both of the above reasons, it is good style to always include the braces (for both the if part and the else part), even when they enclose only a single statement.

  3. If you have an else part, it is usually better to use a "positive" condition than a negated one:
    Poor style Better style
    if (!danger) {
        System.out.println("Relax.");
    }
    else {
        System.out.println("Run away!");
    } 
    if (danger) {
        System.out.println("Run away!");
    }
    else {
        System.out.println("Relax.");
    } 
    if (x != 100) {
        System.out.println("You could do better.");
    }
    else {
        System.out.println("Perfect score!");
    }
    if (x == 100) {
        System.out.println("Perfect score!");
    }
    else {
        System.out.println("You could do better.");
    }

    This is so that when you read your program, you don't have to think "Let's see--it's not the case that danger is false, so that means there is danger, so I should run away." Or, "If I didn't not get 100, I got a perfect score."