Conditionals

Programming Languages · Java Basics · 12 min

Let your program make decisions with if, else and switch.

Comparisons

A comparison asks a yes/no question and gives back a boolean: true or false.

> bigger, < smaller, >= at least, <= at most, == equal, != not equal. (Numbers use ==; Strings use .equals().)

int x = 5;
System.out.println(x > 3); // true
  • Print whether age is at least 18.

  • Print whether age is equal to 21.

if and else

if runs a block of code only when its condition is true. else runs when it's false. Exactly one of the two blocks runs.

if (score > 50) {
    System.out.println("You win");
} else {
    System.out.println("Try again");
}
  • If temperature is greater than 25, print Hot day. Otherwise, print Nice day.

  • Change temperature to 18 and run again. Now the else block runs.

More choices: else if

Need more than two options? Chain else if. Java checks each condition from the top and runs the first one that's true, then skips the rest.

if (n > 0) {
    System.out.println("positive");
} else if (n < 0) {
    System.out.println("negative");
} else {
    System.out.println("zero");
}
  • Print A if score is 90 or more, B if it's 70 or more, and C otherwise.

And, or, not

Combine conditions with:

  • && (and): true only if both sides are true
  • || (or): true if at least one side is true
  • ! (not): flips true to false and back
if (hungry && hasFood) {
    System.out.println("Eat!");
}
  • If age is at least 18 and hasTicket is true, print Come in.

  • If age is under 12 or isHoliday is true, print Free snack.

  • Print !hasTicket.

switch

switch picks one option by matching a value exactly. Each case is one possible value. default runs when nothing matches.

End each case with break, or Java keeps running into the next case too.

switch (size) {
    case 1:
        System.out.println("Small");
        break;
    default:
        System.out.println("Other");
}
  • Write a switch on day: 1 prints Monday, 2 prints Tuesday, 3 prints Wednesday, and default prints Some other day.

Put it together: ticket prices

A cinema charges:

  • under 12: Price: 5
  • 65 or older, or a student: Price: 7
  • everyone else: Price: 12
  • Use if, else if and else to print the right price for age and isStudent.

  • Change age to 30 and isStudent to true. It should still print Price: 7.

More in Java Basics

Previous: Strings · Next: Loops