Java if selects a statement or block when a boolean condition is true. An optional else supplies the alternative. An else-if chain tests alternatives in order and executes the first matching branch. Nested conditions place one decision inside another when the second question only matters after the first succeeds.
The challenge is not the braces alone. You must choose conditions that match the rule, order overlapping branches correctly and make every boundary understandable. This lesson separates those decisions with examples you can trace before running.
Make the condition a boolean question
Write if (condition) followed by a block. The condition must have type boolean, such as balance >= price or isLoggedIn. Java does not treat a nonzero int as true. The block may contain several statements; keeping braces even around one statement prevents mistakes when adding another action later.
An else belongs to the associated if and runs when its condition is false. The two branches are alternatives, so both do not execute for one evaluation. A statement after the entire if-else runs regardless of which branch was selected, unless the branch transfers control through return or another abrupt action. This positioning matters for status messages: placing Approved after the conditional prints it even for the rejected branch.
Order else-if branches from the intended priority
An else-if chain stops after the first true condition. Later conditions are not evaluated after a match. If you classify scores using score >= 90 and score >= 70, test ninety first so a high score does not get caught by the broader seventy condition.
This ordering is different from several separate if statements. A score of ninety-five makes both comparisons true, so independent if statements can print two classifications. Choose a chain when exactly one category should apply. A final else can cover the remaining cases, but it does not validate the input automatically. If negative scores are invalid, add validation before classifying rather than assigning them the lowest grade without explanation.
Include or exclude boundaries deliberately
The difference between > and >= decides whether the exact threshold passes. For a discount available at a total of fifty, use total >= 50. If it applies only above fifty, use total > 50. State the business rule in ordinary language before selecting the operator.
Test values just below, at and just above each threshold. For a score boundary of seventy, sixty-nine, seventy and seventy-one are more informative than three values far away from it. When values are floating-point measurements, consider whether rounding or approximation affects the decision. For beginner examples use integers to focus on control flow, then define units and rounding rules explicitly when introducing decimal inputs.
Nest only when the dependency helps
A nested if expresses a dependent question. For instance, first check whether an account exists; only then check whether it is active. This makes the prerequisite visible and prevents operations that need a valid reference from occurring too early.
Too many levels can hide the main action behind indentation. If both requirements simply need to hold, combine them with &&. If a method should stop immediately for an invalid state, an early return can reduce nesting. These are design alternatives, not mandatory rewrites. Keep separate nested branches when they need distinct messages, such as Account missing versus Account inactive. Combining those failures into one boolean may lose useful feedback even though the success condition remains correct.
Avoid accidental empty statements and dangling else
A semicolon immediately after if (condition) is an empty controlled statement. The block that follows is then independent and can run regardless of the condition. This can be syntactically valid, making it a logic problem rather than a reliable compiler error.
Without braces, an else associates with the nearest unmatched if. A reader’s indentation does not change that association. Use braces to make the relationship explicit, particularly when nesting. Do not place a semicolon between an if block and its else, because that separates the structure incorrectly. When a branch behaves unexpectedly, mark the exact block boundaries and identify which condition controls each statement before changing comparisons.
Practice with explained solutions
Task 1. Classify a temperature as Freezing below zero, Mild from zero through twenty-four, and Hot at twenty-five or above.
Solution. Test the low range first, then temperature < 25, then else. Check -1, 0, 24 and 25.
Task 2. Simplify a nested pair of checks that both require hasTicket and gateOpen, with no separate failure messages.
Solution. Use if (hasTicket && gateOpen) around the success action. Keep nesting if the two failures need different explanations.
Java Summary
- An else-if chain chooses the first matching branch, so order overlapping thresholds carefully.
- Use braces to make nested branch ownership explicit.
- Validate inputs separately from classification and test values around each boundary.
- Continue with loop types.
Java Examples
Each example shows the code, the output it produces and what each part does.
Choose between two outcomes
Save this complete program as BalanceCheck.java. Compile with javac --release 17 BalanceCheck.java and run with java BalanceCheck.
public class BalanceCheck {
public static void main(String[] args) {
int balance = 18;
int price = 20;
if (balance >= price) {
System.out.println("Purchase allowed");
} else {
System.out.println("Insufficient balance");
}
}
}Insufficient balanceLine-by-line explanation
- Lines 1 to 11Eighteen is not at least twenty, so Java skips the first block and runs the else block. Changing balance to twenty permits the purchase because >= includes equality. The comparison does not subtract money; it only selects a branch. A real purchase needs a separate update after permission is confirmed.
Select one score category
Save this complete program as ScoreCategory.java. Compile with javac --release 17 ScoreCategory.java and run with java ScoreCategory.
public class ScoreCategory {
public static void main(String[] args) {
int score = 95;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 70) {
System.out.println("Pass");
} else {
System.out.println("Review needed");
}
}
}ExcellentLine-by-line explanation
- Lines 1 to 8The first condition succeeds and stops the chain. Although ninety-five also satisfies score >= 70, that later condition is not evaluated.
- Lines 9 to 12Reversing the two conditions would print Pass for this score, revealing why branch priority matters. This example assumes score has already been validated within the permitted range.
Keep dependent failure messages distinct
Save this complete program as AccountAccess.java. Compile with javac --release 17 AccountAccess.java and run with java AccountAccess.
public class AccountAccess {
public static void main(String[] args) {
boolean accountExists = true;
boolean accountActive = false;
if (accountExists) {
if (accountActive) {
System.out.println("Access granted");
} else {
System.out.println("Account inactive");
}
} else {
System.out.println("Account missing");
}
}
}Account inactiveLine-by-line explanation
- Lines 1 to 8The outer condition succeeds, so Java asks the inner question. Because accountActive is false, it prints the inner failure message.
- Lines 9 to 15The outer else is skipped because the account exists. Set accountExists to false and the inner condition is not evaluated at all. The separate messages justify nesting here rather than replacing everything with one combined condition.
Common Java Mistakes
Overlapping ranges in separate if statements
Do not classify overlapping ranges with unrelated if statements unless multiple results are intentional. For mutually exclusive outcomes, use an else-if chain or nonoverlapping conditions. Do not hide invalid input inside a convenient final else. The condition that decides a grade is not automatically a complete validation rule for the number supplied.
Java FAQ
Does else need a condition?
No. It represents the remaining alternative after its associated if condition fails. Use else if when another specific condition needs evaluation.
Can an if branch contain another if?
Yes. The inner branch is considered only when control reaches it. Braces clarify which else belongs to which if.
Which if does an else belong to?
An else always pairs with the nearest preceding if that doesn't already have one, whatever the indentation suggests. This "dangling else" can attach a branch to the wrong decision. Braces around every branch make the pairing explicit.
How do I reduce deeply nested if statements?
Combine conditions that must all be true with &&, and in methods handle invalid cases first with an early return or throw, often called guard clauses. The main logic then sits at the left margin instead of three or four levels deep.
Do I need else after a branch that returns?
No. When an if branch ends with return, the code after it only runs when the condition was false, so an else adds nesting without changing behaviour. Many style guides prefer dropping it to keep the main path unindented.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What category does score 95 receive if >=70 is checked before >=90?
What happens to an if body when a stray semicolon follows its condition?
Java Quiz
2 questions to check what you learned.
How many matching branches can an else-if chain execute?
- One
- Every true branch
- None even if true
What does if (ready); introduce?
- An empty controlled statement
- A required separator
- An else branch