Java If Statement

The Java If Statement is one of the most useful decision making statement in real world programming. It allows the compiler to test the condition first and, depending upon the result it will execute the statements. If the test condition is true then only statements with in the if statement is executed.

Java If Statement Syntax

From the above code snippet, If the test condition inside the If statement is true, then the statements (Statement 1, Statement 2, Statement 3, ……., Statement n) will be executed, otherwise all these statements will be skipped. Let us see the flow chart for better understanding.

Flow Chart of a Java If Statement

Following picture will show you the flow chart behind this If Statement in Java

If the test condition is true then STATEMENT 1 is executed followed by STATEMENT N. If the condition is False then STATEMENT N is executed because it is out of the if condition block and it has nothing to do with the condition result. Let us see one example for better understanding.

Java If Statement example

This Java program allows the user to enter any positive integer and it will check whether a number is Positive or Not using the if statement

NOTE: If statement does not required the curly brackets to hold single statement but for multiple or group of statements it is mandatory. It is always good practice to use curly brackets following the If statements.

OUTPUT

From the below screenshot you can observe that, we entered 25 as Number and this program will check whether 25 is greater than 1 or not. As we all know that it is True, it is printing (System.ot.println statement) inside the curly brackets ({}}.

Let us change the value to check what happens if the condition fails? (number < 1).

It print nothing because we don’t have nothing to print after the if statement block. Hope you are confused with the result, let us see one more example.

Java If Statement example 2

This Java program allows the user to enter any positive integer and it will check whether a number is Positive or Not using the if statement