If-Else Statement in Java: Syntax, Else-If Ladder, Nested If and Examples

The if-else statement in Java lets a program choose what to do based on a condition. Java evaluates a boolean expression: if it’s true, the if block runs; if it’s false, the else block runs (when there is one). Adding else if lets you check several conditions in order and run only the first one that matches.

Before you start: the examples use loops to test several values at once, so it helps to have read For Loop in Java. The previous lesson was Labeled Statements in Java.

Key Takeaways

  • The condition inside if ( ) must be a boolean. Java never treats numbers or strings as true or false.
  • In an else if ladder, conditions are checked top to bottom, and only the first true branch runs.
  • An else always pairs with the nearest unmatched if. Braces make the pairing explicit.
  • Compare strings with .equals(), not ==.
  • Use if-else for ranges and combined conditions; use switch for one value compared against fixed constants.

Types of If Statements in Java

FormUse it whenBranches that can run
ifSomething should happen only sometimes0 or 1
if-elseYou need exactly one of two outcomesExactly 1
else if ladderYou have three or more possible outcomesAt most 1 (exactly 1 with a final else)
Nested ifA second decision makes sense only after the first passesDepends on both

The if Statement in Java

Syntax

Example 1: A Simple if

Code (Java 21):

Output:

Fever detected. Please rest.Check complete.

With temperature = 37.0, only “Check complete.” would print. The if block is simply skipped.

What Can Go Inside the Condition?

Anything that produces a boolean:

  • a comparison: marks >= 40, age != 0
  • a boolean variable: isLoggedIn
  • a method that returns boolean: name.isEmpty()
  • a combination using && (AND), || (OR), and ! (NOT)

A number does not work. if (itemsInCart) with an int fails with “incompatible types: int cannot be converted to boolean”. Write if (itemsInCart > 0) instead.

The if-else Statement in Java

Syntax

Whiteboard
Loading diagram...

StartIs the condition true?Run the if blockRun the else blockContinue with the nextstatement

Exactly one of the two blocks runs, never both and never neither.

Example 2: Voting Eligibility (Testing Both Branches)

Code (Java 21):

Output:

21: eligible to vote
16: not eligible yet, 2 year(s) to go
18: eligible to vote

Testing the boundary value (18) matters. Writing age > 18 by mistake would wrongly reject 18-year-olds.

Else-If Ladder in Java

When there are more than two outcomes, chain conditions with else if.

Syntax

Example 3: Grade Calculator

Code (Java 21):

Output:

95 -> A90 -> A
76 -> B
40 -> D
39 -> F
101 -> Invalid marks
-5 -> Invalid marks
Whiteboard
Loading diagram...

Java walks down the ladder and stops at the first “Yes”. The remaining checks are never evaluated.

Dry Run for marks = 76
CheckConditionResultAction
176 < 0 || 76 > 100falsego to next
276 >= 90falsego to next
376 >= 75truegrade = "B", skip the rest
—>= 60, >= 40, elsenot evaluated—

Notice that 76 >= 60 and 76 >= 40 are also true, but they’re never checked. Order decides the answer.

Why Does Condition Order Matter in an Else-If Ladder?

Put the lowest threshold first and every passing student lands in the same grade:

Code (Java 21):

Output:

95 -> D76 -> D
45 -> D

The A and B branches can never run. Rule: with >= checks, start from the highest threshold. With <= checks, start from the lowest.

Nested If-Else in Java

A nested if is an if inside another if. The inner check runs only when the outer one passes.

Example 4: Leap Year Program (Nested vs Combined)

The leap-year rule has three layers: divisible by 4, except centuries, unless divisible by 400.

Code (Java 21):

Output:

2024: nested=true, one-line=true1900: nested=false, one-line=false
2000: nested=true, one-line=true
2026: nested=false, one-line=false

Both versions agree on every year. The nested form mirrors the rule step by step; the one-line form combines it with && and ||.

Guideline: one or two levels of nesting is fine. At three or more, look for a flatter version using &&, an else if ladder, or an early exit (continue in a loop, return in a method).

Example 5: Largest of Three Numbers

Code (Java 21):

Output:

Largest of 12, 45, 7 is 45Largest of 9, 9, 3 is 9
Largest of -4, -10, -1 is -1

Using >= instead of > handles ties (9, 9, 3) correctly. By the second check we already know a isn’t the largest, so comparing b with c is enough.

Logical Operators and Short-Circuit Evaluation

&& and || are short-circuit operators: Java stops evaluating as soon as the answer is known.

  • A && B: if A is false, B is never evaluated.
  • A || B: if A is true, B is never evaluated.

That makes the order of the checks a safety feature:

Code (Java 21):

Output:

 No data or low average

Swap the two checks (total / count > 50 && count != 0) and the division runs first:

 Exception in thread "main" java.lang.ArithmeticException: / by zero	at WrongOrderAnd.main(WrongOrderAnd.java:5)

Rule: put the “is it safe?” check (not zero, not null, in range) on the left of &&.

How to Compare Strings in an If Condition in Java

== checks whether two variables point to the same object; .equals() checks whether the text is the same.

Code (Java 21):

Output:

literal == "java"   : truebuilt == "java"     : false
joined == "java" : false
joined.equals("java"): true
equalsIgnoreCase : true
null-safe check: not confirmed

Why == sometimes “works”: identical string literals share one object, so literal == "java" is true. Strings built at runtime (user input, concatenation, new String) are separate objects, so == returns false even when the text matches. Code that relies on == passes simple tests and then fails with real input.

  • Use a.equals(b) for exact text, and a.equalsIgnoreCase(b) to ignore case.
  • Write "yes".equals(input) (literal first). It returns false instead of crashing when input is null.

Ternary Operator vs If-Else in Java

When an if-else only chooses a value, the ternary operator condition ? valueIfTrue : valueIfFalse does it in one line:

Code (Java 21):

Output:

7 is odd / odd12 is even / even

Use the ternary for a simple either/or value. Use if-else when a branch runs statements, has side effects, or has more than two outcomes. Nested ternaries quickly become hard to read.

If-Else vs Switch in Java

SituationBetter choiceExample
Ranges (>=, <)if-elseGrades, tax slabs, age groups
Conditions on different variablesif-elseage >= 18 && hasId
One variable compared against fixed constantsswitchDay number → day name, menu choice
Complex boolean logicif-elseLeap-year rule

A switch can’t express marks >= 90 directly, so ranges stay with if-else. You’ll study switch in full in the next lesson, Switch Statement in Java.

Common Mistakes With If-Else in Java

Mistake 1: The Dangling Else

Code (Java 21):

Output:

Without braces:Account is empty
With braces:
Done

The balance is 500, yet “Account is empty” printed. An else pairs with the nearest unmatched if (here, if (isPremium)), no matter how the code is indented. Braces fix the pairing.

Mistake 2: Missing Braces Around Two Statements

Code (Java 21):

Output:

Reorder placed.Stock = 25

Without braces, only the first statement belongs to the if. The indentation is misleading, and a reorder was placed for healthy stock. Fix: always use braces.

Mistake 3: A Semicolon After the Condition

Code (Java 21):

Output:

 Speeding fine issued!

The ; ends the if with an empty body, so the block below always runs, and a driver at 40 gets fined. Fix: no semicolon after if (…).

Mistake 4: = Instead of ==

With an int, the compiler catches it:

 AssignInt.java:4: error: incompatible types: int cannot be converted to boolean        if (attempts = 3) {
^
1 error

With a boolean, it compiles and silently changes the variable:

Code (Java 21):

Output:

Admin panel opened!
isAdmin is now true

A non-admin got admin access. Fix: writeif (isAdmin). Never compare a boolean with== true.

Mistake 5: An Extra Statement Between if and else

 ElseWithoutIf.java:7: error: 'else' without 'if'        else
^
1 error

The second println ends the if, leaving the else with nothing to attach to. Braces fix it.

Mistake 6: Putting a Condition After else

 ElseCondition.java:6: error: not a statement        } else (x > 0) {
^
ElseCondition.java:6: error: ';' expected
} else (x > 0) {
^
2 errors

else never takes a condition. Write else if (x > 0).

Mistake 7: Comparing Decimals With ==

Code (Java 21):

Output:

Not equal with ==, total = 0.30000000000000004Equal within tolerance

Decimal values like 0.1 can’t be stored exactly in binary. Compare double values within a small tolerance.

Best Practices

  1. Always use braces, even for a one-line body.
  2. In range ladders, order checks from highest to lowest (for >=), and put validation (invalid input) first.
  3. Add a final else to catch unexpected values, even if it only prints an error.
  4. Keep nesting to two levels; combine related conditions with &&.
  5. Put the safety check on the left of && (count != 0 && …, s != null && …).
  6. Use .equals() for strings, with the literal first for null safety.
  7. Write if (isReady), not if (isReady == true).
  8. Test boundaries: the exact threshold, one below, one above, and invalid values.

Real-World Example: Electricity Bill Calculator

Slab billing is a classic else-if task: each slab has its own rate.

Code (Java 21):

Output:

80 units: Rs 240.00180 units: Rs 700.00
350 units: Rs 2021.25
-20 units: invalid meter reading

For 350 units: 100 × 3 + 100 × 5 + 150 × 7.5 = 1925, plus a 5% surcharge = 2021.25. The rates are illustrative, not a real tariff. The program uses all three tools from this lesson: a guard check for invalid input, an else-if ladder for the slabs, and a separate if for the surcharge.

Other everyday uses: login checks, discount rules, tax and shipping slabs, form validation, game rules, and access control.

Practice Problems

  1. Easy: Print whether a number is positive, negative, or zero.
  2. Easy: Check whether a character is a vowel or a consonant. Hint: || across five vowels, or "aeiou".indexOf(ch) != -1.
  3. Easy–Medium: Given three side lengths, print whether they form a valid triangle and whether it is equilateral, isosceles, or scalene.
  4. Medium: Calculate income tax using slabs (choose your own rates), validating that income isn’t negative.
  5. Medium: Read a username and password (as strings) and print “Welcome”, “Wrong password”, or “Unknown user”. Hint: .equals() and nested if.

Try them in the ExamAdda online compiler.

Interview Questions on If-Else in Java

1. Can the condition of an if be an int in Java?
No. It must be boolean. if (count) fails with “int cannot be converted to boolean”; write if (count > 0).

2. In an else-if ladder, how many branches run?
At most one: the first one whose condition is true. With a final else, exactly one runs.

3. What is the dangling else problem?
In nested ifs without braces, it’s ambiguous which if an else belongs to. Java pairs it with the nearest unmatched if. Braces remove the ambiguity.

4. Why shouldn’t you compare strings with ==?
== compares object references. Strings created at runtime can have the same text but be different objects. Use .equals().

5. What does if (flag = true) do when flag is boolean?
It assigns true to flag, and the condition is always true. It compiles, which is why it’s dangerous.

6. What is short-circuit evaluation?
With &&, the right side is skipped if the left is false; with ||, it’s skipped if the left is true. It lets you write safe checks like x != 0 && y / x > 2.

7. When would you use switch instead of if-else?
When one variable is compared against several fixed constants. Ranges and mixed conditions stay with if-else.

8. What’s the output of if (5 > 3); System.out.println("A");?
A is printed. The semicolon ends the if with an empty body, so the print always runs.

Article Summary

  • if, if-else, the else if ladder, and nested if let a program choose between paths based on a boolean condition.
  • An else-if ladder runs only the first true branch, so the order of conditions decides the result.
  • An else pairs with the nearest unmatched if; braces prevent dangling-else and missing-brace bugs.
  • Use .equals() for strings, a tolerance for doubles, and put safety checks on the left of &&.
  • Prefer if-else for ranges and combined conditions, the ternary for simple value choices, and switch for fixed constants.

Conclusion

The if-else statement is how a Java program makes decisions, and most if-else bugs come from three places: condition order, missing braces, and the wrong kind of comparison. Order your ladders carefully, always use braces, and test the boundary values, and your conditional logic will hold up. Next, learn a cleaner way to handle one value compared against many constants in Switch Statement in Java, and practise with ExamAdda practice questions.

Previous lesson: Labeled Statements in Java
Next lesson: Switch Statement in Java

References