Nested if
- Java course
- Beginner
- Lesson 38/116
- 4 min
Learn nested if blocks.
Nested if
An if block can contain another if. This is called a nested if. The inner condition is only tested when the outer condition is also true.
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("Can drive");
}
}Here the license is checked only when age is 18 or above. If age is younger, the inner block never runs. Nested if is used when multiple conditions must hold together.
A nested if example
A nested if can also be written with logical operators. The two snippets below are equivalent:
// Nested
if (age >= 18) {
if (hasLicense) {
System.out.println("Can drive");
}
}
// Logical and
if (age >= 18 && hasLicense) {
System.out.println("Can drive");
}If two conditions can be simply AND-ed, prefer && over nesting. Nested if is more readable when the inner block has extra code or needs its own else.
Practice Weather advisor
Write a Main class with a main method. Assign 25 to int temp and false to boolean raining. Inside if (temp > 20) use if (!raining) to print System.out.println("Picnic").
Sample solution
public class Main {
public static void main(String[] args) {
int temp = 25;
boolean raining = false;
if (temp > 20) {
if (!raining) {
System.out.println("Picnic");
}
}
}
}Expected output
Picnic
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does the inner block run in a nested if?
- When outer is false
- Only when inner is true
- When outer is true and inner is true Correct answer
- Always
Explanation: The inner block runs when both conditions are true.
2 Complete the nested condition
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (____) {
System.out.println("Can drive");
}
}
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("Can drive");
}
}
Explanation: The inner condition checks hasLicense.
3 Match the nested if concepts
| Term | Meaning |
|---|---|
if (a) |
Outer condition |
if (b) |
Inner condition |
&& |
Logical and |
true && true |
Inner runs |