Java If Statement
The if statement in Java allows you to execute a block of code only when a specified condition is true.
1. Syntax of the If Statement
The basic syntax of an if statement in Java is:
if (condition) {
// code to be executed if condition is true
}
Here, condition
is a boolean expression that evaluates to either true
or false
. If the condition is true
, the code inside the braces will execute; otherwise, it will be skipped.
2. Flow Diagram of If Statement
The diagram below illustrates the flow of execution for an if statement:
3. Examples for the If Statement
1. Check if a Number is Positive
This example checks whether a number (x
) is positive. If it is, a message is printed to the 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 this program, the if
statement checks whether the variable x
is greater than 0. Since x
is 10, the condition is true, and the message “x is positive.” is printed.
2. Check if a Number is Even
This example determines if a number (x
) is even by checking if the remainder when dividing by 2 is zero.
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 even.
Here, the program checks whether the remainder of x
divided by 2 equals 0. Since 10 is evenly divisible by 2, the condition evaluates to true and “x is even.” is printed.
3. If Statement with a False Condition
This example shows what happens when the condition in an if
statement is false. In this case, the code inside the if block is skipped.
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 3 is not an even number (3 % 2 does not equal 0), the code inside the if block does not execute. Only “end of program” is printed.
Conclusion
In this tutorial, we learned how to use the if statement in Java to control the flow of your program based on conditions. With clear examples, we demonstrated how to check if a number is positive, how to determine if a number is even, and what happens when a condition is false.