Nested If - Else
Part of the Fundamentals section of Coddy's Java journey — lesson 32 of 73.
We can nest if-else if-else statements within each other. This allows us to create hierarchical decision-making structures.
Keep in mind that deeply nested
if statements can make code harder to read and maintain.For example:
if (age > 18) {
if (hasLicense) {
System.out.println("You can drive");
} else {
System.out.println("Get a license first");
}
} else {
System.out.println("Too young to drive");
}
It can be infinitely nested:
if (condition1) {
if (condition2) {
if (condition3) {
// runs only when condition1, condition2 and condition3 are all true
...
}
}
}Challenge
BeginnerCreate a program that checks if someone can ride a rollercoaster. The requirements are:
- Must be at least 12 years old
- Must be taller than 150cm
- If they meet both requirements but are under 15, they need adult supervision
Print exactly these messages for each case:
- If too young:
Sorry, you're too young - If not tall enough:
Sorry, you're not tall enough - If under 15 and no adult:
Sorry, you need an adult with you - If under 15 with adult:
You can ride with adult supervision! - If 15 or older and tall enough:
You can ride by yourself!
Cheat sheet
You can nest if-else if-else statements within each other to create hierarchical decision-making structures:
if (age > 18) {
if (hasLicense) {
System.out.println("You can drive");
} else {
System.out.println("Get a license first");
}
} else {
System.out.println("Too young to drive");
}
Nesting can be done infinitely:
if (condition1) {
if (condition2) {
if (condition3) {
// if condition1, condition2 and condition3 are true
...
}
}
}Note: Deeply nested if statements can make code harder to read and maintain.
Try it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt(); // Don't change this line
int height = scanner.nextInt(); // Don't change this line
boolean hasAdult = scanner.nextBoolean(); // Don't change this line
// Write your code below
scanner.close();
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else