Explain it simply
Explain it simply
It is like stopping at a junction and deciding: "if it is raining, take an umbrella, otherwise wear a hat". if asks one question; when the answer is true the program takes the first road, and when it is false it takes the else road. Add else if branches and the junction gets three or four roads.
The key point is that the program follows only one road. It asks the questions from top to bottom, and as soon as one answer is yes it takes that road and never asks the remaining questions.
Problem → Why → Solution
The problem: a 95 mark only shows "Pass"
A teacher writes a grading program, tries marks of 30 and 60, sees Fail and Pass, and is happy. But a student with 95 gets "Pass" instead of Distinction. The code has no syntax error and every single condition is true to its words; the problem is the order.
public class Main {
public static void main(String[] args) {
int mark = 95;
if (mark >= 40) {
System.out.println("Pass"); // 95 >= 40 is true: stops here
} else if (mark >= 80) {
System.out.println("Distinction"); // can never be reached
} else {
System.out.println("Fail");
}
}
}Why does this happen?
An else if chain runs the first branch whose condition is true and skips the rest. Every mark of 80 or more is also 40 or more, so when mark >= 40 is checked first, the Distinction branch can never be reached. The compiler cannot catch this kind of logic error, so you must order the ranges from the strictest (>= 80) downwards.
Core concept: one boolean, one path
The condition inside if's parentheses must be a boolean (true or false). Unlike JavaScript or Python, Java does not treat 0, "" or null as false: int count = 3; if (count) {...} is the compile error "incompatible types: int cannot be converted to boolean". You always write an expression that produces a boolean, such as count > 0, name != null or list.isEmpty().
In an if / else if / else chain, Java tests the conditions from top to bottom and runs only the first block whose condition is true. If none is true, the else block runs, and without an else nothing happens. When ranges overlap (>= 80 sits inside >= 40), the stricter condition must come first. Combine conditions with && and ||, keeping guards like != null on the left.
Braces {} are optional, but without them if controls only the single statement that follows. An indented second line sits outside the if and always runs, because Java ignores indentation completely. Using braces even on one-line ifs is the safe habit.
When you are only choosing between two values, the ternary operator condition ? a : b is shorter than if / else: String label = stock > 0 ? "In stock" : "Sold out";. Nested ternaries quickly become unreadable, though, so keep them for simple choices. When one variable is compared against many fixed values, the switch from the next lesson is the better tool.
A variable declared inside a block only exists inside that block. Declare String message = "Pass"; inside an if block and you cannot use message after the block; you get a "cannot find symbol" error. Declare the variable before the chain and assign it in every branch instead. The Java compiler only lets you read it afterwards when every branch assigns it, a rule called definite assignment.
public class Main {
public static void main(String[] args) {
int stock = 0;
String label = stock > 0 ? "In stock" : "Sold out";
System.out.println(label);
String role = "editor";
boolean loggedIn = true;
if (!loggedIn) {
System.out.println("Please log in");
} else if ("admin".equals(role) || "editor".equals(role)) {
System.out.println("Can edit");
} else {
System.out.println("Read only");
}
}
}- Evaluate the first condition
- If true, run that block and leave
- If false, move to the next condition
- If none is true, run the else block
A chain never runs more than one block, which is why the order is part of the logic.
General pattern
if (strictestCondition) {
// runs when the first condition is true
} else if (nextCondition) {
// runs only if every condition above was false
} else {
// runs when nothing above was true (optional)
}
Type value = condition ? valueIfTrue : valueIfFalse;Each condition is a boolean in parentheses. Add as many else if branches as you need; else is optional. Wrap every block in braces. The last line is the ternary form for picking one of two values.
Example: turning a mark into a result
This example is the fixed version of the problem code: the strict >= 80 test sits at the top and >= 40 comes after it. Let us trace which lines actually run with mark = 75.
public class Main {
public static void main(String[] args) {
int mark = 75;
if (mark >= 80) {
System.out.println("Distinction");
} else if (mark >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}Code breakdown
- Line 3
int mark = 75;This is the value being tested. Change it to 85, 40 and 39 to see all three branches.
- Line 5
if (mark >= 80) {75 >= 80 is false, so the Distinction block is skipped and Java moves to the next condition. As the strictest range it has to come first.
- Line 7
} else if (mark >= 40) {Reaching this line already guarantees mark < 80, so this branch really means "40 to 79". 75 >= 40 is true, so Pass is printed.
- Line 9
} else {This block is reached only when both conditions above are false (mark < 40). In this run the Pass branch already ran, so else is never considered.
Pass- mark >= 80? false
- mark >= 40? true
- Print "Pass"
- Leave the chain
mark 80 or more
Distinction
mark 40 to 79
Pass
mark below 40
Fail
Pattern matching with instanceof
When you need to check an object's type and then use it as that type, Java 16 and later let you use an instanceof pattern. input instanceof String s is true when input is a String and also creates the String variable s, so you no longer write the cast yourself. You can use s right away on the right side of &&, because the right side only runs when the left side is true.
public class Main {
static String describe(Object input) {
if (input instanceof Integer n) {
return "Integer, next is " + (n + 1);
} else if (input instanceof String s && !s.isBlank()) {
return "Text with " + s.strip().length() + " characters";
} else {
return "Unsupported input";
}
}
public static void main(String[] args) {
System.out.println(describe(41));
System.out.println(describe(" hello "));
System.out.println(describe(" "));
System.out.println(describe(3.5));
}
}The output is Integer, next is 42, then Text with 5 characters, then Unsupported input twice: the all-space String fails the isBlank() check, and 3.5 is a Double.
In real projects
Where this shows up in real projects
Backend methods are full of guard clauses: at the top of the method, an if checks for invalid input and returns or throws straight away, as in if (order == null) return; or if (amount <= 0) throw .... That keeps the main logic from drifting rightwards into nested ifs. Payment approval, age restrictions, shipping-fee tiers and discount tiers are else if chains, and a wrong order there charges customers the wrong price.
Teams test tier logic by deliberately picking boundary values such as 39, 40, 79 and 80, because >= versus > slips and ordering mistakes only show up at those edges. instanceof patterns appear where code handles values by type, for example Object values parsed from JSON or different kinds of events in a handler.
Common mistakes
Common mistakes
1. Ordering overlapping ranges wrongly
Testing mark >= 40 before mark >= 80 turns the Distinction branch into dead code, and the compiler does not warn you. Order from the strictest condition down, or spell out the full range, as in mark >= 40 && mark < 80.
2. Indenting two lines without braces
With two indented lines after if (x > 10), only the first belongs to the if; the second always runs whatever x is. Java does not look at indentation. Put { } around every block.
3. Testing a boolean with = true
if (isAdmin = true) compiles, stores true in isAdmin and so always runs the branch. Write if (isAdmin) and if (!isAdmin) instead; you never need == true, and the = typo can no longer happen.
Mini challenge
Mini challenge: cinema ticket prices
Write a program that works out a cinema ticket price from the customer's age and membership.
- Return -1 for an age below 0 or above 120 (a guard clause)
- Under 12 pays 3000, 60 and over pays 3500, everyone else 5000 MMK
- Members aged 12 and over get 1000 off
- show() prints a separate message for an invalid age
public class Main {
static int ticketPrice(int age, boolean member) {
// TODO: guard clause for impossible ages (return -1)
// TODO: else if chain for the three age groups
// TODO: member discount for ages 12 and over
return 0;
}
static void show(int age, boolean member) {
// TODO: "Age 30 (member): 4000 MMK" or "Age -3: invalid age"
}
public static void main(String[] args) {
show(8, true);
show(30, false);
show(30, true);
show(65, true);
show(-3, false);
}
}Expected: The program prints these five lines: Age 8 (member): 3000 MMK Age 30: 5000 MMK Age 30 (member): 4000 MMK Age 65 (member): 2500 MMK Age -3: invalid age
Show hint
Put the guard clause at the top of the method. Declare int price; and let every branch of the chain assign it. The " (member)" text can be added with a ternary.
Show solution
public class Main {
static int ticketPrice(int age, boolean member) {
if (age < 0 || age > 120) {
return -1;
}
int price;
if (age < 12) {
price = 3000;
} else if (age >= 60) {
price = 3500;
} else {
price = 5000;
}
if (member && age >= 12) {
price -= 1000;
}
return price;
}
static void show(int age, boolean member) {
int price = ticketPrice(age, member);
String who = "Age " + age + (member ? " (member)" : "");
if (price < 0) {
System.out.println(who + ": invalid age");
} else {
System.out.println(who + ": " + price + " MMK");
}
}
public static void main(String[] args) {
show(8, true);
show(30, false);
show(30, true);
show(65, true);
show(-3, false);
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An if condition must be a boolean; Java never treats 0 or null as false.
- An else if chain runs only the first true branch, so order ranges from the strictest.
- Put braces around every block, because Java ignores indentation.
- Use ? : to pick between two values and instanceof patterns to check types.