Link Search Menu Expand Document

Exercise 2: Operators on Boolean Types

Please do this exercise in a group with other students.

Go through the questions and discuss the answers within your group. Write them down/remember them to share later with the class.

  1. Exercise 2: Operators on Boolean Types
    1. Objective
    2. Questions
      1. Question 1
      2. Question 2
      3. Question 3
      4. Question 4

Objective

Goal of this exercise is to get a basic understanding of

  • how to work with booleans in Java

Questions

Try to find the answers within your group (in case of questions/problems => ask one of your teachers!)

Question 1

Let’s meet the first operator we can use with one boolean:

this is the ! operator (exclamation mark)

class Main {
    public static void main(String[] args) {
        boolean b = ?;
        System.out.println(!b);
    }
}

Try to find out what the ! operator does by assigning different values to b.

Question 2

Let’s meet another operator we can use with two booleans:

this is the || operator (two vertical bars)

class Main {
    public static void main(String[] args) {
        boolean a = ?;
        boolean b = ?;
        System.out.println(a || b);
    }
}

Try to find out what the || operator does by assigning different values to a and b.

Question 3

Let’s meet another operator we can use with two booleans:

this is the && operator (two ampersands)

class Main {
    public static void main(String[] args) {
        boolean a = ?;
        boolean b = ?;
        System.out.println(a && b);
    }
}

Try to find out what the && operator does by assigning different values to a and b.

Question 4

Given the following program defining two variables

class Main {
    public static void main(String[] args) {
        int a = 16;
        int b = 8;
        
    }
}

How would you

  • implement a check (using boolean operators and number operators) that tells you if both a and b are greater than 10 (hint: implement and then rerun program with different values assigned to a and b to check that it is correct)
  • implement a check (using boolean operators and number operators) that tells you if either a or b are smaller than 10 (hint: implement and then rerun program with different values assigned to a and b to check that it is correct)
  • implement a check (using boolean operators and number operators) that tells you if a is at least two times bigger than b (hint: implement and then rerun program with different values assigned to a and b to check that it is correct), i.e. for a = 16 and b = 8 your check should return true (as a is two times b)