Example
Evaluate whether 20 is greater than 18; if true, print a specified text.
if (20 > 18) {
System.out .println("20 is greater than 18");
}
|
Definition and Usage
The “if” statement delineates a segment of Java code to be executed when a condition evaluates to true.
In Java, the following conditional statements are available:
- Employ “if” to designate a code block for execution if a particular condition is true.
- Utilize “else” to designate a code block for execution if the same condition is false.
- Implement “else if” to introduce a new condition for testing if the initial condition is false.
- Employ “switch” to designate multiple alternative code blocks for execution.
More Examples
Example
Utilize an if statement to evaluate variables.
int x = 20;
int y = 18;
if (x > y ) {
System.out .println("x is greater than y");
}
|
Example
Employ the else statement to define a code block for execution if the condition is false.
int time = 20;
if (time < 18) {
System.out .println("Good day.");
} else {
System.out .println("Good evening.");
}
// Outputs "Good evening."
|
Example
Utilize the else if statement to introduce a new condition if the initial condition is false.
int time = 20;
if (time < 18) {
System.out .println("Good morning.");
} else if (time < 20) {
System.out .println("Good day.");
} else {
System.out .println("Good evening.");
}
// Outputs "Good evening."
|