if/else Statements
An if/else
statement is critical to decision-making in programs and is one of the most valuable tools in Java programming. With an if/else
statement, you can specify which block of code to execute based on the outcome of a condition. If the condition is false
, the code in the else
branch will execute.
Relational Operators:
Relational operators can be used to specify a condition in an if
statement.
-
Less than:
a < b
-
Less than or equal to:
a <= b
-
Greater than:
a > b
-
Greater than or equal to:
a >= b
-
Equal to:
a == b
-
Not equal to:
a != b
if Statement
- The
if
statement allows you to specify a block of code to execute if its condition istrue
. If the condition isfalse
, its block of code will not execute.
else if Statement
- The
else if
statement is used to specify an additional condition to test if the condition for theif
statement evaluates tofalse
. If the condition for theelse if
statement istrue
, its block of code will execute. If it isfalse
, its block of code will not execute.
else Statement
- The
else
statement allows you to specify a block of code to execute if the condition for theif
statement evaluates tofalse
.
Examples
One-Way Selection Statement
An if
statement is also known as a one-way selection statement.
if (17 > 12) {
System.out.println("The condition evaluated to true.");
}
Output:
The condition evaluated to true.
Two-Way Selection Statement
An if-else
statement is also known as a two-way selection statement.
if (17 < 12) {
System.out.println("The condition evaluated to true.");
}
else {
System.out.println("In the else block");
}
Output:
In the else block
Multi-Selection Statements
An if-else if-else
statement is also known as a multi-selection statement.
if (17 < 12) {
System.out.println("Less Than.");
}
else if (17 == 17) {
System.out.println("Equal To.");
}
else {
System.out.println("Greater Than.");
}
Output:
Equal To
Tips
You can also use nested if
statements to evaluate multiple conditions that must be true
before a block of code is executed. For example:
if (17 >= 17) {
if (17 == 17) {
System.out.println("EQUAL");
}
}