Home › Learn › Java › Decisions and methods

Comparisons and booleans

Lesson 6 of 40. Ask questions about values and combine the answers.

Comparisons produce a boolean: a == b, a != b, a < b, a <= b, and so on. == compares numbers, characters, and booleans; for strings use .equals. Booleans combine with && (and), || (or), and ! (not): age >= 18 && age < 65. Both sides of && and || are booleans; x == 1 || 2 is a compile error, a reminder that Java does not guess.

Store a comparison in a boolean variable and it reads like a fact: boolean warm = temperature > 20;. The later branches of && and || are skipped when the answer is already known, which is how s != null && s.isEmpty() avoids touching a null string.

int age = 20;
boolean adult = age >= 18;
boolean teen = age >= 13 && age <= 19;
System.out.println(adult + " " + teen + " " + !adult);   // true false false

Your task

Using temperature from the starter, set warm to whether it is above 20, mild to whether it is between 15 and 25 inclusive, extreme to whether it is below 0 or above 35, and sameAsYesterday to whether today and yesterday hold the same text (they are strings, so compare with equals).

Hint 1

warm = temperature > 20; mild = temperature >= 15 && temperature <= 25;

Hint 2

extreme = temperature < 0 || temperature > 35; sameAsYesterday = today.equals(yesterday);

Show the solution
public class Main {
    static int temperature = 23;
    static String today = "cloudy";
    static String yesterday = "cloudy";
    static boolean warm = temperature > 20;
    static boolean mild = temperature >= 15 && temperature <= 25;
    static boolean extreme = temperature < 0 || temperature > 35;
    static boolean sameAsYesterday = today.equals(yesterday);

    public static void main(String[] args) {
        System.out.println(warm + " " + mild + " " + extreme + " " + sameAsYesterday);
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.