Java Arena
Step 4 of 6

And, or, not

Conditions can be combined:

  • a && b (and) is true when both a and b are true.
  • a || b (or) is true when at least one of them is true.
  • !a (not) is true when a is false.

A range check is the classic use of &&: a number is between 1 and 10 when it's at least 1 and at most 10.

int number = 7;
if (number >= 1 && number <= 10) {
    System.out.println("In range");
}
if (number < 1 || number > 10) {
    System.out.println("Out of range");
}
System.out.println(!(number > 5));
Output
In range
false

Java checks && and || from left to right and stops as soon as the answer is known: in a && b, when a is false, b isn't looked at.

Your task

Challenge 1 of 3

Read an age and, using a single if with &&, print Teenager for ages 13 to 19 and Not a teenager for any other age. For the input 15 the program prints:

Teenager

Challenge 2

Read a temperature and print Extreme temperature when it's below -20 or above 40, and OK otherwise. Use ||. For the input 45 the program prints:

Extreme temperature

Challenge 3

Read a number and print Out of range when it's not between 1 and 10, and In range otherwise. Write the condition with ! in front of the range check, as !( ... && ... ). For the input 12 the program prints:

Out of range