if statement

The if statement is a conditional branch statement. The syntax of the if statement is either one of these two:

if (booleanExpression) {
    statement(s)
}
if (booleanExpression) {
    statement(s)
} else {
    statement(s)
}

If booleanExpression evaluates to true, the statements in the block following the if statement are executed. If it evaluates to false, the statements in the if block are not executed. If booleanExpression evaluates to false and there is an else block, the statements in the else block are executed.

For example, in the following if statement, the if block will be executed if x is greater than 4.

if (x > 4) {
    // statements
}

In the following example, the if block will be executed if a is greater than 3. Otherwise, the else block will be executed.

if (a > 3) {
    // statements
} else {
    // statements
}

Note that the good coding style suggests that statements in a block be indented.

If the expression to be evaluated is too long to be written in a single line, it is recommended that you use two units of indentation for subsequent lines. For example.

if (numberOfLoginAttempts < numberOfMaximumLoginAttempts
        || numberOfMinimumLoginAttempts > y) {
    y++;
}

If there is only one statement in an if or else block, the braces are optional.

if (a > 3)
    a++;
else
    a = 3;

If there are multiple selections, you can also use if with a series of else statements.

if (booleanExpression1) {
    // statements
} else if (booleanExpression2) {
    // statements
} 
...
else {
    // statements
}

For example

if (a == 1) {
    System.out.println("one");
} else if (a == 2) {
    System.out.println("two");
} else if (a == 3) {
    System.out.println("three");
} else {
    System.out.println("invalid");
}

In this case, the else statements that are immediately followed by an if do not use braces.