Java if-else Statement

In the last lesson you learned about the Java if statement. But most decisions need a backup plan for when the condition is false. For that second path, Java gives you if-else.

๐Ÿค” Why do we need else?

A plain if covers only the true case. When the condition is false, nothing happens. The else block fills that gap:

  • A plain if asks โ€œshould I do this?โ€
  • An if-else asks โ€œwhich of these two things should I do?โ€
  • The else runs when the if condition turns out false.
  • Think login: password correct, let them in; wrong, show an error. Both paths matter.
  • Two-way forks are everywhere: pass or fail, even or odd, in stock or out, allowed or blocked.

๐Ÿด The fork-in-the-road analogy

A fork in the road splits in two. You pick one path, never both. That is exactly how if-else behaves:

  • The condition is the signpost at the fork.
  • True sign, take the if path; false sign, take the else path.
  • You always walk one path, never both, never neither.
  • So one block is guaranteed to run. With a plain if, the road could just end.

๐Ÿงฉ The if-else syntax

You write an if with its block, then else with its own block right after the closing brace.

if (condition) {
// โœ… runs when the condition is true
} else {
// โœ… runs when the condition is false
}

Key points about this shape:

  • The condition goes in round brackets after if, and must be a boolean (true or false).
  • The else keyword has no condition; it just catches the false case.
  • Each block sits in its own curly braces { }.
  • Exactly one block runs: true runs the if and skips the else; false does the opposite.

This checks whether a number is even or odd using the modulus operator %, which gives the remainder after division.

int number = 7;
if (number % 2 == 0) {
System.out.println("Even"); // runs when remainder is 0
} else {
System.out.println("Odd"); // runs otherwise
}

Walking through it:

  • number % 2 is the remainder of 7 divided by 2, which is 1.
  • It checks 1 == 0, which is false.
  • So the if is skipped and the else runs, printing โ€œOddโ€.

Output

Odd

Change number to 8: 8 % 2 is 0, 0 == 0 is true, the if runs, and you get โ€œEvenโ€. Same code, different value, different path.

๐Ÿ” Two separate ifs vs one if-else

Writing two separate if statements when you mean one if-else is risky. This tries to print Pass or Fail using two separate checks:

int score = 35;
// โš ๏ธ Works, but fragile: two separate, unlinked checks
if (score >= 40) {
System.out.println("Pass");
}
if (score < 40) {
System.out.println("Fail");
}

It prints โ€œFailโ€ correctly, but it is fragile:

  • Java tests the score twice, once per if. Wasted work.
  • The two conditions are not linked, so nothing keeps them in step.
  • Edit one and forget the other, and they overlap. Change the second to score <= 40 and a score of 40 prints both Pass and Fail.

Here is the same thing as one if-else:

int score = 35;
// โœ… Clearer and safer: one linked two-way decision
if (score >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}

Why this wins:

  • The score is checked once.
  • The else covers everything the if did not.
  • No second condition to sync, so the paths can never overlap.
  • When two if conditions are opposites, fold them into one if-else.

๐ŸŽฏ A pass or fail check, worked through

Letโ€™s trace the classic two-way decision fully.

int score = 35;
if (score >= 40) {
System.out.println("Result: Pass");
} else {
System.out.println("Result: Fail");
}

Step by step:

  • Java reads score, which is 35.
  • It checks score >= 40, which means 35 >= 40. That is false.
  • Because the condition is false, the if block is skipped.
  • The else block runs and prints โ€œResult: Failโ€.

Output

Result: Fail

Change score to 75: 75 >= 40 is true, so the if runs and prints โ€œResult: Passโ€. One block always runs, and which one depends entirely on the value.

โŒจ๏ธ if-else with user input

With input you do not know the answer ahead of time. This reads a number and tells the user whether it is positive or negative, pulling together Scanner, a comparison, and if-else.

import java.util.Scanner;
public class SignCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number >= 0) {
System.out.println("That is zero or positive");
} else {
System.out.println("That is negative");
}
}
}

We read the number, then check number >= 0:

  • Type 5: condition true, the if block runs.
  • Type -8: condition false, the else block runs.
  • The program responds differently based on real input.

Output

Enter a number: -8
That is negative

๐Ÿ”— Combining if-else with logical operators

A condition need not be a single comparison. Join several with the logical operators && (and) and || (or). The joined expression still gives one true or false, so it slots straight into an if-else.

Here a shopper gets a discount only if they are a member and spent at least 100.

boolean isMember = true;
int amount = 120;
if (isMember && amount >= 100) {
System.out.println("You get a 10% discount");
} else {
System.out.println("No discount this time");
}

The && needs both parts true. The shopper is a member and 120 is at least 100, so both sides are true and the if block runs.

Output

You get a 10% discount

The || operator needs only one side true. Here a user can log in with either the correct password or a valid backup code.

boolean rightPassword = false;
boolean validBackupCode = true;
if (rightPassword || validBackupCode) {
System.out.println("Login success");
} else {
System.out.println("Login failed");
}

The password is wrong, but the backup code is valid. With ||, one true side is enough, so the whole condition is true and the user is let in.

Output

Login success

The structure never changes. Only the condition grows richer: one true-or-false result, two paths, one of them runs.

When both paths simply pick a value, you can use the ternary operator instead. Here is an if-else that chooses a label:

int score = 35;
String result;
if (score >= 40) {
result = "Pass";
} else {
result = "Fail";
}
System.out.println(result);

And here is the exact same logic with the ternary, written in one line:

int score = 35;
String result = score >= 40 ? "Pass" : "Fail"; // โœ… same result, shorter
System.out.println(result);

Read it as a question: condition, then ?, then the value if true, then :, then the value if false. So score >= 40 ? "Pass" : "Fail" means โ€œis the score 40 or more? if yes, Pass, if no, Failโ€.

if-else or the ternary?

Use the ternary when you are only picking one value, like setting a label or a number. Use a full if-else when each path does real work, runs several lines, or calls methods. The ternary is shorter, but a packed ternary is hard to read, so do not force it.

โš ๏ธ Common Mistakes

A few if-else slip-ups trip up almost everyone at first.

Using two separate ifs that should be one if-else. Exact-opposite conditions belong together; splitting them lets the halves drift apart and overlap.

// โŒ Avoid: two unlinked checks, can both run if edited wrong
if (age >= 18) { System.out.println("Adult"); }
if (age <= 18) { System.out.println("Minor"); } // 18 hits BOTH
// โœ… Good: one if-else, paths can never overlap
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}

Forgetting the braces. Without braces, only the first line after the if belongs to it; the rest runs no matter what.

// โŒ Avoid: no braces, "Welcome" prints even when blocked
if (allowed)
System.out.println("Access granted");
System.out.println("Welcome"); // this is NOT inside the if
// โœ… Good: braces make the grouping clear and correct
if (allowed) {
System.out.println("Access granted");
System.out.println("Welcome");
}

Getting the condition logic wrong. A wrong condition sends the wrong block running. Common slips: = (assign) instead of == (compare), or flipping > and <.

// โŒ Avoid: > should be >=, so a score of exactly 40 wrongly fails
if (score > 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
// โœ… Good: >= includes the boundary value 40
if (score >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}

Giving else its own condition. The else never takes a condition; it catches everything the if missed. Writing else (x > 5) is a syntax error. For a second condition use else if, which is the next lesson.

โœ… Best Practices

Habits that keep your two-way decisions clean and safe.

  • Use if-else for two opposite paths. One outcome when true, another when false.
  • Always use braces. Even single-line branches; it stops the no-braces bug and makes grouping obvious.
  • Fold opposite ifs into one if-else. The else covers the second case for free and can never drift out of sync.
  • Reach for the ternary for simple value choices. Picking one of two values reads shorter and cleaner.
  • Keep both paths meaningful. If the else would be empty, drop it; a plain if is enough.

๐Ÿงฉ What Youโ€™ve Learned

Quick recap:

  • โœ… The if-else statement handles two paths: one when the condition is true, one when it is false.
  • โœ… Exactly one block runs, never both and never neither, like picking one path at a fork.
  • โœ… Two opposite separate ifs are clearer and safer rewritten as one if-else.
  • โœ… The else never takes its own condition; it catches everything the if did not.
  • โœ… Conditions can combine with logical operators && and || and still feed one if-else.
  • โœ… For a simple two-way choice of a single value, the ternary is a shorter option.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    In an if-else, how many blocks run?

    Why: Exactly one block runs: the if block if the condition is true, otherwise the else block.

  2. 2

    When does the else block run?

    Why: The else block runs only when the if condition is false.

  3. 3

    Can else have its own condition like else (x > 5)?

    Why: A plain else takes no condition. It catches everything the if did not. For another condition, use else if.

  4. 4

    What does this print: int n = 4; if (n % 2 == 0) print Even else print Odd?

    Why: 4 % 2 is 0, so the condition is true and the if block prints Even.

๐Ÿš€ Whatโ€™s Next?

You can handle two paths now. But many decisions have more than two outcomes, like grades A, B, C, and F. For that you chain conditions together with else if. Letโ€™s learn the ladder next.

Java Nested if Statement

Share & Connect