In Java, as in many other programming languages, the “if…else” statement is a fundamental control structure that allows your program to make decisions based on certain conditions. It provides the ability to execute different blocks of code depending on whether a specified condition evaluates to true or false. In this article, we’ll dive into the usage of “if…else” statements in Java, along with examples to help you understand how they work.
The Basics of If…Else Statements
The “if…else” statement in Java follows a straightforward structure:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
condition
represents an expression that is evaluated as either true or false.- The code within the first block
{ ... }
is executed if the condition is true. - The code within the second block
{ ... }
is executed if the condition is false.
Example 1: Simple If…Else
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are not yet an adult.");
}
In this example, the program evaluates the age
variable. If the age is greater than or equal to 18, it prints “You are an adult.” Otherwise, it prints “You are not yet an adult.”
Example 2: If…Else If…Else
You can also use multiple conditions with “if…else if…else.”
int score = 85;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 70) {
System.out.println("Good job!");
} else if (score >= 50) {
System.out.println("Passed.");
} else {
System.out.println("Try again.");
}
In this example, the program checks the value of the score
variable and provides different feedback based on the score achieved.
Example 3: Nested If…Else
“if…else” statements can also be nested inside each other.
int x = 10;
int y = 5;
if (x > 5) {
if (y > 2) {
System.out.println("Both conditions are met.");
} else {
System.out.println("Second condition is not met.");
}
} else {
System.out.println("First condition is not met.");
}
This code first checks if x
is greater than 5, and if it is, it checks if y
is greater than 2. The appropriate message is printed based on the evaluation of these conditions.
The “if…else” statement is a crucial tool for making decisions and creating flexible, responsive Java programs. By using conditions, you can direct the flow of your code and execute different actions based on specific criteria. Understanding and mastering “if…else” statements is a fundamental skill in Java programming and will open the door to building more complex and dynamic applications.