Learn/Java/4. Making decisions
Lesson 4 of 15
Sign in

Java, lesson 4

Making decisions

So far every program has run the same statements every time. Real programs react to their input: a game ends when lives reach zero, a shop gives a discount above some amount. You express that with conditions.

if, else if, else

Java checks each condition from top to bottom and runs the first block whose condition is true, then skips the rest. The else block runs only if nothing above matched. The condition must be a boolean; Java will not treat 0 or an empty string as false the way some languages do.

Comparison operators

OperatorMeaning
==equal to

2 exercises to try what you just read.

Exercise 1

Ticket prices

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

!=not equal to
< <=less than (or equal)
> >=greater than (or equal)

Each comparison produces a boolean you can store: boolean passed = score >= 50;

Strings are different. For text, use equals, not ==. The == operator checks whether two variables point to the same object, which is not the same as having the same letters:

Combining conditions

  • && (and) is true when both sides are true.
  • || (or) is true when at least one side is true.
  • ! (not) flips true and false.

&& and || are short-circuit operators: if the left side already decides the answer, the right side is never evaluated. That lets you write guards such as name != null && name.length() > 3 safely.

switch expressions

When you compare one value against a list of fixed options, a switch expression is cleaner than a long if chain. Modern Java uses the arrow form, which never "falls through" to the next case:

A switch expression produces a value, so it must cover every possibility; default handles anything not listed. It works with int, char, String, enums and more.

The conditional operator

For a quick either-or value there is condition ? valueIfTrue : valueIfFalse:

Use it for short choices only; an if statement is clearer for anything bigger.

Further reading

  • Control flow statements (dev.java)
  • Switch expressions (dev.java)
  • Operators (dev.java)

A cinema charges by age. Read one whole number, the visitor's age, and print the price:

AgeOutput
below 0Invalid age
0 to 4Price: 0
5 to 17Price: 8
18 to 64Price: 12
65 and abovePrice: 7

Sample input:

Sample output:

A year is a leap year if it is divisible by 4, except years divisible by 100, which are not leap years unless they are also divisible by 400. Read a year and print either <year> is a leap year or <year> is not a leap year.

Try to write the rule as one boolean expression using %, && and ||.

Sample input:

Sample output:

int score = 72;

if (score >= 90) {
    System.out.println("Gold");
} else if (score >= 70) {
    System.out.println("Silver");
} else {
    System.out.println("Keep practising");
}
String answer = in.readLine();
if (answer.equals("yes")) { ... }            // correct
if (answer.equalsIgnoreCase("YES")) { ... }  // ignores upper/lower case
boolean weekend = day.equals("Sat") || day.equals("Sun");
if (age >= 13 && age <= 19) {
    System.out.println("Teenager");
}
if (!weekend) {
    System.out.println("Alarm at 7:00");
}
String sound = switch (animal) {
    case "cat" -> "Meow";
    case "dog" -> "Woof";
    case "cow", "ox" -> "Moo";      // several labels share one result
    default -> "...";
};
String label = count == 1 ? "item" : "items";
30
Price: 12
2024
2024 is a leap year