Java If

Java If Statement is used to execute a block of code based on the result of a given condition.

Syntax

The syntax of If conditional statement in Java is

if (condition) {
     //statement(s)
 }

where condition is a boolean expression.

If the condition evaluates to true,  if code block is executed. Else, continue with the statements after If statement.

The following diagram depicts the flow of program execution for If statement based on the result to condition.

ADVERTISEMENT
Java If Statement Flow Diagram

Examples

In the following example, we chec the condition that if x is positive, and printing a message to console.

Main.java

public class Main {
    public static void main(String[] args) {
        int x = 10;
        if(x > 0){
            System.out.println("x is positive.");
        }
    }
}

Output

x is positive.

In the following example, we check if x is an even number.

Main.java

public class Main {
    public static void main(String[] args) {
        int x = 10;
        if(x % 2 == 0){
            System.out.println("x is even.");
        }
    }
}

Output

x is positive.

Now, let us take a value for x, such that the condition x % 2 == 0 becomes false.

Main.java

public class Main {
    public static void main(String[] args) {
        int x = 3;
        if(x % 2 == 0){
            System.out.println("x is even.");
        }
        System.out.println("end of program");
    }
}

Output

end of program

Since, the condition becomes false for given value of x, if-block does not execute.

Conclusion

In this Java Tutorial, we learned how to write If statement, and how to use an If statement to implement conditional execution of a block of code in Java, with the help of examples.