ESC
Type to search...
Dashboard / Java notes / Concepts / Basics / Part i

05 - Condition

P1 · Updated · Source
#java/basics #l0 #concept #must-know #status/known

Conditional Statements (if / else if / else)

What is it?

A conditional statement lets your program make decisions - execute one block of code or another depending on whether a condition is true or false.

Syntax

Simple if

if (condition) {
    // code runs only if condition is true
}

if + else

if (condition) {
    // runs if condition is true
} else {
    // runs if condition is false
}

if + else if + else

if (condition1) {
    // runs if condition1 is true
} else if (condition2) {
    // runs if condition1 is false AND condition2 is true
} else {
    // runs if ALL above conditions are false
}

Note Only one block ever runs in an if-else if-else chain. Java checks from the top - as soon as one condition is true, it runs that block and skips the rest.

Full Example

Scanner scanner = new Scanner(System.in);
int number = Integer.parseInt(scanner.nextLine());

if (number > 0) {
    System.out.println("Positive");
} else if (number < 0) {
    System.out.println("Negative");
} else {
    System.out.println("Zero");
}

Condition Ordering Rule - Most Specific First

Put the most restrictive/specific condition at the top. If a broader condition comes first, it will catch cases you meant for a later branch.

// BAD - wrong order
if (number > 0) {
    System.out.println("Positive");
} else if (number > 100) {  // ← This NEVER runs! number > 0 catches it first.
    System.out.println("Large positive");
}

// GOOD - specific first
if (number > 100) {
    System.out.println("Large positive");
} else if (number > 0) {
    System.out.println("Positive");
} else {
    System.out.println("Zero or negative");
}

Nested Conditions

You can put an if inside another if:

if (age >= 18) {
    if (hasID) {
        System.out.println("Entry allowed");
    } else {
        System.out.println("Need ID");
    }
} else {
    System.out.println("Too young");
}

Tip Deeply nested conditions get hard to read. Prefer combining conditions with && and || where possible.

Combining Conditions with Logical Operators

if (age >= 18 && hasTicket) {
    System.out.println("Welcome!");
}

if (isAdmin || isOwner) {
    System.out.println("Access granted");
}

Gotchas

  • No semicolon after the condition: if (x > 0) - not if (x > 0);. A semicolon ends the if right there, and the block below always runs
  • The else block is optional - only add it if you need to handle the false case
  • Forgetting else if and writing two ifs instead: the second if always gets checked even if the first was true - subtle bug
  • Comparing Strings? Use .equals(), not == inside conditions

Related: Comparison, Loops, Calculations, Methods