if / else / else-if
Programs need to make decisions. Show a different message based on a score. Block access if age is under 18. Apply a discount only on weekends.
The if statement is how Java makes decisions. It runs a block of code only when a condition is true — and skips it when it's not.
👉 What you'll learn here:
- ›The
ifstatement — run code when a condition is true - ›The
elseclause — what happens when the condition is false - ›
else if— checking multiple conditions in sequence - ›Nested
ifstatements — conditions inside conditions - ›Common mistakes and how to avoid them
🧘 if/else is the most natural concept in programming.
You already think this way: "If it's raining, take an umbrella. Otherwise, leave it at home." Java's if/else is exactly that — translated into code. The syntax is the only new thing to learn here.
The if Statement
The simplest form — run a block of code only if a condition is true.
Syntax:
1if (condition) {
2 // code runs ONLY if condition is true
3}1int score = 85;
2
3if (score >= 60) {
4 System.out.println("You passed!");
5}Output:
You passed!
If score were 45, the condition score >= 60 would be false — the block is skipped and nothing prints.
How it works:
The condition inside ( ) must be a boolean expression — something that evaluates to true or false. Comparison operators (==, !=, >, <, >=, <=) and logical operators (&&, ||, !) are what you'll use most often here.
The else Clause
else runs a block when the if condition is false. Exactly one of the two blocks will always run.
Syntax:
1if (condition) {
2 // runs if condition is true
3} else {
4 // runs if condition is false
5}1int age = 16;
2
3if (age >= 18) {
4 System.out.println("Access granted.");
5} else {
6 System.out.println("You must be 18 or older.");
7}Output:
You must be 18 or older.
💡 Exactly one branch always runs. With if/else, there are no gaps and no overlaps — the program always takes one path or the other. This is different from two separate if statements, where both could run (or neither).
1// Two separate if statements — BOTH can run:
2if (score >= 60) System.out.println("Passed");
3if (score < 60) System.out.println("Failed");
4
5// if/else — exactly ONE runs:
6if (score >= 60) System.out.println("Passed");
7else System.out.println("Failed");The else if Chain
else if lets you check multiple conditions in sequence. Java evaluates them top to bottom and runs the first one that is true — then skips all the rest.
Syntax:
1if (condition1) {
2 // runs if condition1 is true
3} else if (condition2) {
4 // runs if condition1 is false AND condition2 is true
5} else if (condition3) {
6 // runs if condition1 and condition2 are false AND condition3 is true
7} else {
8 // runs if ALL conditions above are false
9}Grade calculator example:
1int marks = 78;
2
3if (marks >= 90) {
4 System.out.println("Grade: A");
5} else if (marks >= 75) {
6 System.out.println("Grade: B"); // ← this runs — 78 >= 75
7} else if (marks >= 60) {
8 System.out.println("Grade: C");
9} else if (marks >= 40) {
10 System.out.println("Grade: D");
11} else {
12 System.out.println("Grade: F");
13}Output:
Grade: B
Even though 78 >= 60 and 78 >= 40 are also true, only the first matching branch runs. Once a condition matches, all remaining else if and else blocks are skipped.
💡 Order matters in else if chains. Always put the most specific (strictest) condition first. If you reversed the grade example — checking >= 40 before >= 90 — every student above 40 would get "Grade D", even those with 95 marks.
Single-Statement Shorthand — No Braces
When an if, else, or else if block contains exactly one statement, the curly braces are optional:
1// With braces:
2if (score >= 60) {
3 System.out.println("Passed");
4}
5
6// Without braces — same result:
7if (score >= 60)
8 System.out.println("Passed");⚠️ Recommendation: always use braces. Omitting them is a known source of bugs. If you add a second statement thinking it's inside the if block — it isn't:
1if (score >= 60)
2 System.out.println("Passed");
3 System.out.println("Congratulations!"); // ← ALWAYS runs, not part of the if!This is a real bug that has caused serious production incidents in major software. Using braces consistently eliminates this entire category of error.
Nested if Statements
You can place if statements inside other if blocks. This is called nesting — use it when a second condition only makes sense after the first is true.
1int age = 22;
2boolean hasTicket = true;
3
4if (age >= 18) {
5 System.out.println("Age check passed.");
6
7 if (hasTicket) {
8 System.out.println("Entry granted — enjoy the event!");
9 } else {
10 System.out.println("You need a ticket to enter.");
11 }
12
13} else {
14 System.out.println("Under 18 — entry not permitted.");
15}Output:
Age check passed.
Entry granted — enjoy the event!
💡 Keep nesting shallow. Deep nesting — if inside if inside if — becomes hard to read and debug quickly. If you find yourself at three or more levels deep, consider restructuring with else if or extracting logic into a separate method.
1// Deep nesting — hard to follow:
2if (isLoggedIn) {
3 if (isAdmin) {
4 if (hasPermission) {
5 // actual logic buried here
6 }
7 }
8}
9
10// Better — early return / guard clauses (once you learn methods):
11if (!isLoggedIn) return;
12if (!isAdmin) return;
13if (!hasPermission) return;
14// actual logic here — flat and clearConditions with Logical Operators
You can combine multiple conditions in one if using && (AND) and || (OR):
1int age = 25;
2int income = 50000;
3
4// AND — both must be true:
5if (age >= 21 && income >= 30000) {
6 System.out.println("Eligible for loan.");
7}
8
9// OR — at least one must be true:
10boolean isWeekend = true;
11boolean isHoliday = false;
12
13if (isWeekend || isHoliday) {
14 System.out.println("Store closed today.");
15}
16
17// NOT — reverses the condition:
18boolean isLoggedIn = false;
19
20if (!isLoggedIn) {
21 System.out.println("Please log in to continue.");
22}Range check — checking if a value is between two bounds:
1int temperature = 24;
2
3if (temperature >= 20 && temperature <= 30) {
4 System.out.println("Comfortable temperature.");
5}⚠️ Common range mistake:
1// Wrong — mathematically impossible (nothing is simultaneously < 0 AND > 100):
2if (score < 0 && score > 100) { ... }
3
4// Correct — use OR for "outside range":
5if (score < 0 || score > 100) {
6 System.out.println("Invalid score.");
7}Comparing Strings in Conditions
Never use == to compare Strings in if conditions — use .equals():
1String role = "admin";
2
3// Wrong:
4if (role == "admin") { // ❌ may not work correctly
5 System.out.println("Admin access");
6}
7
8// Correct:
9if (role.equals("admin")) { // ✅ always works
10 System.out.println("Admin access");
11}
12
13// Case-insensitive comparison:
14if (role.equalsIgnoreCase("ADMIN")) { // ✅ "admin", "Admin", "ADMIN" all match
15 System.out.println("Admin access");
16}A Complete Example
1import java.util.Scanner;
2
3public class ATM {
4 public static void main(String[] args) {
5
6 Scanner scanner = new Scanner(System.in);
7
8 double balance = 15000.0;
9
10 System.out.print("Enter withdrawal amount: ₹");
11 double amount = scanner.nextDouble();
12
13 if (amount <= 0) {
14 // Invalid input
15 System.out.println("Amount must be greater than zero.");
16
17 } else if (amount > balance) {
18 // Insufficient funds
19 System.out.println("Insufficient balance.");
20 System.out.println("Your balance: ₹" + balance);
21
22 } else if (amount % 100 != 0) {
23 // ATMs dispense in multiples of 100
24 System.out.println("Amount must be a multiple of ₹100.");
25
26 } else {
27 // All checks passed — process withdrawal
28 balance -= amount;
29 System.out.println("Dispensing: ₹" + amount);
30 System.out.println("Remaining balance: ₹" + balance);
31 }
32
33 scanner.close();
34 }
35}Sample runs:
Enter withdrawal amount: ₹500
Dispensing: ₹500.0
Remaining balance: ₹14500.0
Enter withdrawal amount: ₹20000
Insufficient balance.
Your balance: ₹15000.0
Enter withdrawal amount: ₹350
Amount must be a multiple of ₹100.
This example shows a real pattern — a chain of else if blocks each handling a specific invalid case, with the final else handling the success case. Only one branch ever runs, and every possible input is handled.
Common Mistakes
1. Using = instead of ==
1int x = 5;
2if (x = 10) { } // ❌ compile error — this assigns 10 to x, not a comparison
3if (x == 10) { } // ✅ compares x to 102. Missing braces leading to logic errors
1if (score >= 60)
2 System.out.println("Passed");
3 System.out.println("Good job!"); // ❌ always runs — not inside the if
4
5if (score >= 60) {
6 System.out.println("Passed");
7 System.out.println("Good job!"); // ✅ only runs when score >= 60
8}3. Wrong logical operator for range check
1if (age < 0 && age > 120) { } // ❌ impossible — nothing satisfies both
2if (age < 0 || age > 120) { } // ✅ outside valid range4. Putting more specific conditions after less specific ones
1// Wrong order — marks = 95 hits first condition and gets "D":
2if (marks >= 40) System.out.println("Grade D");
3else if (marks >= 90) System.out.println("Grade A"); // never reached!
4
5// Correct order — most specific first:
6if (marks >= 90) System.out.println("Grade A");
7else if (marks >= 40) System.out.println("Grade D");5. Comparing Strings with ==
1if (name == "Arjun") { } // ❌ unreliable
2if (name.equals("Arjun")) { } // ✅ always correct6. Forgetting else — gaps in logic
1if (score >= 60) {
2 status = "Pass";
3}
4// What if score < 60? 'status' is never assigned — potential bug!
5
6if (score >= 60) {
7 status = "Pass";
8} else {
9 status = "Fail"; // ✅ every case handled
10}Quick Reference
1// Basic if
2if (condition) {
3 // runs when true
4}
5
6// if-else
7if (condition) {
8 // runs when true
9} else {
10 // runs when false
11}
12
13// else-if chain
14if (condition1) {
15 // runs when condition1 is true
16} else if (condition2) {
17 // runs when condition1 false, condition2 true
18} else {
19 // runs when all conditions false
20}
21
22// Nested if
23if (outerCondition) {
24 if (innerCondition) {
25 // runs when BOTH are true
26 }
27}
28
29// Common conditions
30if (x == 10) { } // equals
31if (x != 10) { } // not equals
32if (x > 10 && x < 20) { } // range check
33if (x < 0 || x > 100) { } // outside range
34if (!isActive) { } // negation
35if (name.equals("Arjun")) { } // string comparisonThe 3 Things to Remember From This Page
- ›
else ifruns the first match only — conditions are checked top to bottom. Put the most specific condition first. Once one matches, all remaining branches are skipped. - ›Always use braces
{ }— even for single-statement blocks. Omitting braces is a well-known source of bugs when code is modified later. - ›Never use
==for Strings — use.equals()or.equalsIgnoreCase().==compares object references, not content, and gives unpredictable results with Strings.
Summary
- ›
if— runs a block only when a condition istrue - ›
else— runs when theifcondition isfalse. Exactly one ofif/elsealways runs. - ›
else if— checks multiple conditions in sequence. First match wins — the rest are skipped. - ›Nesting —
ifinsideif. Use sparingly — more than two levels becomes hard to read. - ›Logical operators — combine conditions with
&&(AND),||(OR),!(NOT) - ›Always use braces — even for single statements. Prevents a classic category of bugs.
- ›String comparison — use
.equals()not==inifconditions. - ›Order matters — in
else ifchains, put the most specific condition first.
What to Read Next
| Topic | Link |
|---|---|
| switch statement — alternative to long else-if chains | switch Statement → |
| Operators — comparison and logical operators | Operators → |
| Ternary operator — compact one-line if/else | Operators → |
| for loop — repeating code with conditions | for Loop → |
| while loop — looping until a condition is false | while Loop → |