Basic

Control Flow: Conditionals

Make decisions with if/else and switch statements.

What you will see

Weekday

About 2 min of reading

Try It

Make Java decide. Write an if/else chain, combine conditions with and/or, compare Strings safely, and pick among cases with switch, each change flips exactly one line of output.

1

Branch with if / else if / else. Only the first matching condition runs. Set a score and watch the matching letter print, nothing else.

class Main { public static void main(String[] args) { int score = 85; if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else { System.out.println("C"); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
B
Parentheses around the condition are required, and the first true branch wins. Move the score to 85 to see B instead of A.
2

Combine conditions with && (and) and || (or). Two independent if statements each print when their rule matches, a 20-year-old with an ID gets one line but not the discount.

class Main { public static void main(String[] args) { int age = 20; boolean hasId = true; if (age >= 18 && hasId) { System.out.println("Allowed"); } if (age < 13 || age > 65) { System.out.println("Discount"); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Allowed
&& and || short-circuit: evaluation stops as soon as the result is known, which is why the right side of && can be a null check without throwing.
3

Compare two Strings that hold the same characters. Use .equals() for content and == for reference equality. Watch how the two operators disagree for the same pair of strings.

class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; System.out.println(a.equals(b)); System.out.println(a == b); } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
true true
== compares references for objects, which is often a bug with Strings. Always use .equals() to compare String content.
4

Pick among several cases with switch. Shared case labels fall through to the first real body, and break stops the chain. Set the day and watch the matching message print.

class Main { public static void main(String[] args) { String day = "Mon"; switch (day) { case "Mon": case "Tue": System.out.println("Weekday"); break; default: System.out.println("Weekend"); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Weekday
Skip the break and the next case runs too, that is called falling through, and it is one of the most common switch bugs.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A boolean expression is evaluated; the first true condition selects the matching branch.
1 Evaluate the condition expression
↓
2 Compare values with operators
↓
3 First true branch runs
↓
4 Else-if / else runs if none matched
Why this works
Comparison and equality

Use == for primitives, but for String and objects compare with .equals():

String a = "hello";
String b = new String("hello");
System.out.println(a == b);       // false (different objects)
System.out.println(a.equals(b));  // true (same content)

== compares references for objects; .equals() compares logical content.

Short-circuit evaluation

With &&, if the left side is false the right side never runs. With ||, if the left side is true the right side never runs. This is handy for null checks:

if (str != null && str.length() > 5) {
    // safe: short-circuits before calling length()
}

Without short-circuiting, str.length() would throw a NullPointerException.

Examples

If/else branching

Branching on conditions

int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}

Java uses {} blocks (not indentation). Only the first matching branch runs. Parentheses around the condition are required.

Logical operators

Combining conditions

int age = 20;
boolean hasId = true;
if (age >= 18 && hasId) {
    System.out.println("Allowed");
}
if (age < 13 || age > 65) {
    System.out.println("Discount");
}

&& (and), || (or), ! (not) short-circuit: evaluation stops as soon as the result is known.

Switch expressions

Selecting among many cases

String day = "Mon";
switch (day) {
    case "Mon":
    case "Tue":
        System.out.println("Weekday");
        break;
    default:
        System.out.println("Weekend");
}

Each case ends with break to avoid falling through. Newer Java supports switch as an expression returning a value with yield.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Variables and Data Types
Previous Lesson
Variables and Data Types
Next Lesson
Loops and Iteration
Loops and Iteration →