Java If...Else
An if statement runs a block of code only when its condition is true. An else block covers the case where the condition is false.
A true condition runs the block
The condition is true, so the line inside the block prints. The line after the block prints as well.
public class Main {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("Adult");
}
System.out.println("Done");
}
}A false condition skips the block
The condition is false, so the line inside the block stays silent. The line after the block prints on its own.
public class Main {
public static void main(String[] args) {
int age = 12;
if (age >= 18) {
System.out.println("Adult");
}
System.out.println("Done");
}
}Else covers the other case
The first age takes the if block. The second age takes the else block.
public class Main {
public static void main(String[] args) {
int firstAge = 20;
if (firstAge >= 18) {
System.out.println("Adult");
} else {
System.out.println("Child");
}
int secondAge = 9;
if (secondAge >= 18) {
System.out.println("Adult");
} else {
System.out.println("Child");
}
}
}Else if chains the tests
The chain tests its conditions in order. The first true condition decides the line that prints.
public class Main {
public static void main(String[] args) {
int score = 75;
if (score >= 90) {
System.out.println("High");
} else if (score >= 70) {
System.out.println("Middle");
} else {
System.out.println("Low");
}
}
}Example
public class Main {
public static void main(String[] args) {
int temperature = 18;
if (temperature >= 25) {
System.out.println("Warm");
} else if (temperature >= 15) {
System.out.println("Mild");
} else {
System.out.println("Cold");
}
System.out.println("Checked");
}
}Key points
- The if block runs when its condition is true.
- A false condition skips the if block.
- The program continues after a skipped block.
- The else block runs when the condition is false.
- An else if line tests a new condition when the one before it was false.
- Braces group the statements inside a block.
In this example, temperature holds 18. The first condition is false and the second condition is true, so the word Mild prints. The line after the chain prints Checked.
Note
An else block has no condition of its own.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
An if condition is false and the statement has an else block. What runs?