In this tutorial, you will learn about control flow statements using Java if…else statements with the help of examples.
The if…else statement is one of the most fundamental conditional statements in Java programming. It is used to execute a block of code if a specified condition is true or to execute a different block of code if the condition is false.
The general syntax of an if…else statement in Java is as follows:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Here, condition
is a Boolean expression that evaluates to either true or false. If the condition is true, the code inside the first block of braces will be executed, and if it is false, the code inside the second block of braces will be executed.
Let’s see some examples to understand how the if…else statement works in Java.
Example 1:
int age = 20;
if (age >= 18) {
System.out.println("You are an adult");
} else {
System.out.println("You are a minor");
}
In this example, we have declared a variable age
and assigned it a value of 20. The if statement checks whether age
is greater than or equal to 18. Since the condition is true, the code inside the first block of braces will be executed, and the output will be “You are an adult”.
Example 2:
int num = 7;
if (num % 2 == 0) {
System.out.println("The number is even");
} else {
System.out.println("The number is odd");
}
In this example, we have declared a variable num
and assigned it a value of 7. The if statement checks whether num
is divisible by 2 with no remainder. Since the condition is false, the code inside the second block of braces will be executed, and the output will be “The number is odd”.
Example 3:
int num1 = 10;
int num2 = 20;
if (num1 > num2) {
System.out.println("num1 is greater than num2");
} else if (num1 < num2) {
System.out.println("num1 is less than num2");
} else {
System.out.println("num1 is equal to num2");
}
In this example, we have declared two variables num1
and num2
and assigned them values of 10 and 20, respectively. The if statement checks whether num1
is greater than num2
. Since the condition is false, the else if statement is executed, which checks whether num1
is less than num2
. Since the condition is true, the code inside the second block of braces will be executed, and the output will be “num1 is less than num2”.
Note that you can have multiple else if statements to check for more than two conditions.
In summary, the if…else statement is a powerful tool in Java programming that allows you to execute different blocks of code based on a specified condition. By mastering this statement, you can write more complex programs that can make decisions based on user input or other conditions.