Skip to main content
Engineering LibreTexts

13.3: Conditional Statements

  • Page ID
    15237
  • To write useful programs, we almost always need to check conditions and react accordingly. Conditional statements give us this ability. The simplest conditional statement in Java is the if statement:

    if (x > 0) {
        System.out.println("x is positive");
    }
    

    The expression in parentheses is called the condition. If it is true, the statements in braces get executed. If the condition is false, execution skips over that block of code. The condition in parentheses can be any boolean expression.

    A second form of conditional statement has two possibilities, indicated by if and else. The possibilities are called branches, and the condition determines which one gets executed:

    if (x % 2 == 0) {
        System.out.println("x is even");
    } else {
        System.out.println("x is odd");
    }
    

    If the remainder when x is divided by 2 is zero, we know that x is even, and this fragment displays a message to that effect. If the condition is false, the second print statement is executed instead. Since the condition must be true or false, exactly one of the branches will run.

    The braces are optional for branches that have only one statement. So we could have written the previous example this way:

    if (x % 2 == 0)
        System.out.println("x is even");
    else
        System.out.println("x is odd");
    

    However, it’s better to use braces – even when they are optional – to avoid making the mistake of adding statements to an if or else block and forgetting to add the braces.

    if (x > 0)
        System.out.println("x is positive");
        System.out.println("x is not zero");
    

    This code is misleading because it’s not indented correctly. Since there are no braces, only the first println is part of the if statement. Here is what the compiler actually sees:

    if (x > 0) {
        System.out.println("x is positive");
    }
        System.out.println("x is not zero");
    

    As a result, the second println runs no matter what. Even experienced programmers make this mistake; search the web for Apple’s “goto fail” bug.