typestar

If & else in Java

Branching: the if/else chain and the conditional operator.

int hour = 14;

if (hour < 12) {
    System.out.println("morning");
} else if (hour < 18) {
    System.out.println("afternoon");
} else {
    System.out.println("evening");
}

// the conditional operator picks a value, not a branch
var label = hour < 12 ? "am" : "pm";
System.out.println(label);

How it works

  1. if/else if/else runs exactly one branch.
  2. Braces on every branch are the Java habit, even for one-liners.
  3. ? : picks a value inline when a full branch is too much ceremony.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
283
Tokens
83
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 1 of 3 in Flow control, step 8 of 29 in Language basics.

← Previous Next →

If & else in other languages