if-else Statement in Java – Explained with Examples
Programs constantly make decisions: apply a discount or not, allow a login or reject it, choose a tax slab. In Java, the if statement and its partners else and else if are the basic tools for these decisions. They run a block of code only when a boolean condition is true.
This tutorial covers the simple if, if-else, the else-if ladder and nested if, with practical examples, cleaner alternatives and the mistakes that trip up beginners.
1. Forms of the if Statement
| Form | Use it when |
|---|---|
if | You want to run code only when a condition is true. |
if-else | You want to choose between two paths. |
if-else-if ladder | You have several conditions to check in order. |
Nested if | A decision depends on an earlier decision. |
The condition inside the parentheses must be a boolean expression, usually built with relational and logical operators.
2. The Simple if Statement
if (condition) {
// runs only when condition is true
}
public class SimpleIf {
public static void main(String[] args) {
double cartTotal = 1250.0;
if (cartTotal >= 1000) {
System.out.println("You get free delivery!");
}
int age = 15;
if (age >= 18) {
System.out.println("You can vote."); // skipped: condition is false
}
System.out.println("Checks finished.");
}
}
You get free delivery! Checks finished.
When the condition is false, Java simply skips the block and continues with the next statement.
3. The if-else Statement
Add else to run an alternative block when the condition is false. Exactly one of the two blocks runs.
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}
public class IfElseDemo {
public static void main(String[] args) {
int balance = 800, withdrawal = 1200;
if (balance >= withdrawal) {
balance -= withdrawal;
System.out.println("Withdrawal successful. Balance: " + balance);
} else {
System.out.println("Insufficient funds. Balance: " + balance);
}
int year = 2024;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println(year + " is a leap year");
} else {
System.out.println(year + " is not a leap year");
}
}
}
Insufficient funds. Balance: 800 2024 is a leap year
4. The if-else-if Ladder
When there are more than two possibilities, chain conditions with else if. Java checks them from top to bottom and runs the block of the first true condition; the final else catches everything else. Order matters: put the most specific or smallest ranges first.
public class ElectricityBill {
// if-else-if ladder: the first true condition wins
static double bill(int units) {
double amount;
if (units <= 100) {
amount = units * 3.0;
} else if (units <= 200) {
amount = 100 * 3.0 + (units - 100) * 4.5;
} else if (units <= 400) {
amount = 100 * 3.0 + 100 * 4.5 + (units - 200) * 6.0;
} else {
amount = 100 * 3.0 + 100 * 4.5 + 200 * 6.0 + (units - 400) * 7.5;
}
return amount;
}
public static void main(String[] args) {
for (int units : new int[] {80, 150, 320, 500}) {
System.out.printf("%3d units -> Rs. %.2f%n", units, bill(units));
}
}
}
80 units -> Rs. 240.00 150 units -> Rs. 525.00 320 units -> Rs. 1470.00 500 units -> Rs. 2700.00
Because the ladder stops at the first match, the condition units <= 200 does not need to repeat units > 100.
5. Nested if and Guard Clauses
An if inside another if is a nested if. It works, but deep nesting is hard to read. Guard clauses, which check for problem cases first and return early, keep the same logic flat:
public class NestedIf {
static String login(String user, String password, boolean locked) {
if (user.equals("asha")) {
if (locked) {
return "Account locked. Contact support.";
} else if (password.equals("s3cret")) {
return "Welcome, asha!";
} else {
return "Wrong password.";
}
} else {
return "Unknown user.";
}
}
// The same logic with guard clauses (early returns) is flatter and easier to read
static String loginFlat(String user, String password, boolean locked) {
if (!user.equals("asha")) return "Unknown user.";
if (locked) return "Account locked. Contact support.";
if (!password.equals("s3cret")) return "Wrong password.";
return "Welcome, asha!";
}
public static void main(String[] args) {
System.out.println(login("asha", "s3cret", false));
System.out.println(login("asha", "oops", false));
System.out.println(loginFlat("asha", "s3cret", true));
System.out.println(loginFlat("ravi", "x", false));
}
}
Welcome, asha! Wrong password. Account locked. Contact support. Unknown user.
6. Common Pitfalls and Modern Features
public class IfPitfalls {
public static void main(String[] args) {
int stock = 0;
// Pitfall 1: a stray semicolon ends the if; the block always runs
if (stock > 0); {
System.out.println("Pitfall 1: this prints even though stock is 0");
}
// Pitfall 2: without braces, only the first statement belongs to the if
if (stock > 0)
System.out.println("in stock");
System.out.println("Pitfall 2: this line is NOT part of the if");
// Pitfall 3: compare strings with equals(), not ==
String status = new String("ACTIVE");
if (status == "ACTIVE") System.out.println("never printed");
if (status.equals("ACTIVE")) System.out.println("Pitfall 3: equals() works");
// Java 16+: pattern matching in an if condition
Object value = 42;
if (value instanceof Integer n && n > 40) {
System.out.println("Pattern matching: " + n + " is a big Integer");
}
}
}
Pitfall 1: this prints even though stock is 0 Pitfall 2: this line is NOT part of the if Pitfall 3: equals() works Pattern matching: 42 is a big Integer
- Stray semicolon:
if (stock > 0);has an empty body, so the following block always runs. - Missing braces: without
{ }, only the next single statement belongs to theif, whatever the indentation suggests. Always use braces. - Comparing strings with
==: useequals(). - Pattern matching (Java 16+):
if (value instanceof Integer n && n > 40)tests the type, casts and checks in one condition.
7. The Dangling else
In if (a) if (b) x(); else y();, the else belongs to the nearest if (the one testing b), not to the outer one. Braces remove all doubt about which if an else belongs to.
8. Alternatives to Long if-else Chains
- Ternary operator for choosing between two values:
String s = ok ? "Yes" : "No";. See Ternary Operator. - switch for comparing one value against many constants or patterns. See switch Statement.
- Lookup maps (
Map<String, Integer>) or TreeMap.floorEntry() for slabs and ranges. - Polymorphism: replace type-checking chains with overridden methods.
9. Best Practices
- Always use braces, even for one-line bodies.
- Keep conditions simple; extract complex ones into well-named variables or methods.
- Prefer guard clauses over deep nesting.
- Write
if (isReady), notif (isReady == true). - Handle the "else" case deliberately; an unexpected value often deserves an error or log message.
10. Summary
ifruns a block when a boolean condition is true.if-elsechooses between two blocks; theelse-ifladder chooses the first true condition among many.- Nested ifs handle dependent decisions; guard clauses keep them readable.
- Watch for stray semicolons, missing braces and
==on strings. - Use the ternary operator, switch or maps when they express the logic more clearly.
Related Tutorials
Reference: dev.java: Control Flow Statements
Frequently Asked Questions (FAQ)
Q1. What is an if-else statement in Java?
A control statement that runs one block of code when a boolean condition is true and, optionally, another block when it is false.
Q2. Can the if condition be an integer?
No. Java requires a boolean expression. if (count) does not compile when count is an int; write if (count != 0).
Q3. Are braces required in an if statement?
Not when the body is a single statement, but it is strongly recommended to always use them. Without braces, adding a second line later silently puts it outside the if.
Q4. What is an else-if ladder?
A chain of if, else if … else blocks. Conditions are tested in order, and only the block for the first true condition runs.
Q5. How many else-if blocks can I use?
As many as you need; there is no limit. For many fixed values, a switch or a lookup map is usually clearer.
Q6. What is a nested if statement?
An if statement placed inside another if or else block, used when one decision depends on another.
Q7. Is else mandatory?
No. An if can stand alone. Use else only when there is something to do in the false case.
Q8. Why does my if block always run?
Most likely there is a semicolon right after the condition, if (x > 0);, which makes the if-body empty. The following block then runs unconditionally.
Q9. What is the dangling else problem?
With nested ifs without braces, it can be unclear which if an else belongs to. Java always attaches it to the nearest unmatched if. Braces make the intent explicit.
Q10. What is the difference between if-else and switch?
if-else can test any boolean condition, including ranges and combinations. switch compares one value against constants or patterns and is clearer for many fixed cases.
Q11. What is the difference between if-else and the ternary operator?
if-else is a statement that can run any code. The ternary operator is an expression that produces one of two values and is ideal for short assignments.
Q12. What is a guard clause?
An early check that handles an invalid or special case and returns (or throws) immediately, so the main logic does not have to be nested inside else blocks.
Q13. Can I declare variables inside an if block?
Yes, but they exist only inside that block. Declare a variable before the if if you need it afterwards.
Q14. How do I compare strings in an if condition?
Use if (name.equals("Asha")) or the null-safe if ("Asha".equals(name)). == compares references, not text.
Q15. How do I check multiple conditions in one if?
Combine them with && (all must be true) or || (any can be true), using parentheses for clarity: if (age >= 18 && (hasId || isAccompanied)).
Q16. What is pattern matching in an if statement?
Since Java 16, if (obj instanceof String s) checks the type and declares a variable s of that type, which can be used in the condition and in the block, removing a manual cast.
Q17. Does the order of else-if conditions matter?
Yes. Only the first true condition runs. If a broad condition such as marks >= 40 comes before marks >= 85, the second will never be reached.
Q18. Can I use if without a condition in parentheses?
No. The parentheses around the condition are required by Java's syntax.
Q19. Is deep nesting of if statements bad?
It makes code hard to read and test. Use guard clauses, combine conditions, extract methods or use polymorphism to flatten deeply nested logic.
Q20. Can an if statement return a value?
No, if is a statement, not an expression. Use the ternary operator or a switch expression when you need a value, or assign/return inside each branch.