Learn Java · lesson 15 of 61 · about 8 minutes
else if and Nesting
Sell the right ticket for the customer's age: choose between several options with else if, catch impossible values first, and nest decisions.
What you'll learn
- Chain conditions with else if
- Order conditions correctly
- Nest if statements
More than two outcomes
The desk sells three kinds of ticket: children under 12 get a child ticket, people under 65 get an adult ticket, and everyone older gets a senior ticket. That's three outcomes, and if with else only gives two.
else if adds more conditions. They're checked from the top, only the first true branch runs, and else catches whatever is left.
The right ticket
public class Main {
public static void main(String[] args) {
int age = 30;
if (age < 12) {
System.out.println("Child ticket");
} else if (age < 65) {
System.out.println("Adult ticket");
} else {
System.out.println("Senior ticket");
}
}
}Output
Adult ticketOrder matters
Check in one direction. Here that's the youngest first: if age < 65 came first, an 8-year-old would match it and get an adult ticket. And check impossible values before anything else: nobody is below 0 or above 120, so age < 0 || age > 120 goes at the top.
A decision inside a decision
public class Main {
public static void main(String[] args) {
boolean loggedIn = true;
boolean isPlus = false;
if (loggedIn) {
if (isPlus) {
System.out.println("Unlimited fuel");
} else {
System.out.println("Fuel: 5");
}
} else {
System.out.println("Please sign in");
}
}
}Output
Fuel: 5Tip
Java has no elif: it's two words, else if.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.