Overview of This Lesson

Besides arithmetic expressions, relational (or conditional) expressions are also a large part of any programming language. Relational expressions allow your program code to make decisions, repeat a set of statements until a certain condition is met, sort and search for data, and many other important tasks.

Pre-Requisites

Before doing this lesson, make sure you're familiar with Java's data types, how to create and use variables, and how to write arithmetic expressions.

The Boolean Data Type

The boolean primitive data type is used for true/false values. You can write various expressions that result in a boolean, and you can also create boolean variables.

Boolean expressions use relational operators and logical operators. All relational and logical expressions must result in a boolean value of true or false.

Boolean primitive variables can be declared and used in a program, but they will only accept the values true and false. You can't assign any other value to a boolean variable.

Additionally, if you're familiar with the Scanner class, it contains a nextBoolean() method that allows you to retrieve a true/false value from the input source:

import java.util.Scanner;

public class BoolStuff {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.println("True or False: Java was invented by a Canadian.");
        boolean answer = in.nextBoolean();
        System.out.println("Your answer: " + answer);
    }
}

In the program above, the user can type the word "true" or the word "false", and they can type it in any case, and the nextBoolean() method will return the boolean value "true" or "false", as appropriate. For example, try the program - run it and try typing "TRUE", "False", "tRUE", and "FaLsE". Your program will only output the boolean values true or false (in all lower-case). If the value entered by the user can't be translated into a boolean value, then an InputMismatchException occurs and the program crashes (much like it would if you asked for an int or double and the user entered letters).

One way to avoid errors (without using exception handling, which we haven't learned yet) is to grab the boolean input as a String using the Scanner's next() method. Then you can use the parseBoolean() method from the Boolean class (this is a "wrapper class" for the boolean data type). The Boolean.parseBoolean() method is a static method (invoke it using the name of the class Boolean) and it receives a String input/argument. It will examine that string input and turn it into a boolean primitive value: If the string looks like the word "true", then it will return the boolean value true. If the string looks like anything else ("false", "apple", "Fred", etc) then it will return the boolean value false.

import java.util.Scanner;

public class BoolStuff {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.println("True or False: Java was invented by a Canadian.");
        String answer = in.next();

        System.out.println("You typed " + answer);

        boolean boolAnswer = Boolean.parseBoolean(answer);
        System.out.println("That is " + boolAnswer);
    }
}

Test the above program: try typing valid boolean values, and try typing some nonsense values (e.g. "apple"). Go to the JavaDoc API and read about the parseBoolean() method. What does it tell you about why you would get certain results if you enter something like "apple"?

Relational Expressions

Relational expressions are expressions that use relational or condtional operators. These operators should already be familiar from any secondary school math class:

Java Relational Operators
Operation Operator in Java Example
Greeater Than > boolean bool = x > 2;
Greeater Than or Equal To >= boolean bool = x >= 2;
Less Than < boolean bool = x < 2;
Less Than or Equal To <= boolean bool = x <= 2;
Equal To ("double-equals") == boolean bool = x == 2;
Not Equal To != boolean bool = x != 2;

Like many other kinds of operators, relational operators are binary operators: they require two operands - one on the left and one on the right. Sometimes the operands are entire expressions, much like you sometimes see with arithmetic operators.

A relational expression, sometimes also referred to as a conditional expression or condition, includes two operands and one of the relational operators. The relational operators might be represented differently in different languages. For example, != in Java is sometimes written in other programming languages as NOT=, <>, or ~=. Also, in some languages, the == relational operator (pronounced "double equals") is written as =.

A simple example using the double-equals and not-equals operator in Java:

int someVar = 5;
int otherVar = 7;
System.out.println(someVar != otherVar);
System.out.println(someVar == otherVar);

In the first and second statements, we are assigning the value 5 to someVar and the value 7 to otherVar. In the third statement, we are asking if someVar contains a value that is different from the value in otherVar. In this case, the relational expression is someVar != otherVar and its result is the boolean value true. This value is sent to the println() and is displayed on the console. The fourth statement contains the relational expression someVar == otherVar, which results in the boolean value false. Thus, "false" is the output for this statement.

Alternatively, you could have placed the result of these two relational expressions into boolean variables:

int someVar = 5;
int otherVar = 7;
boolean firstStmt = someVar != otherVar;
boolean secondStmt = someVar == otherVar;
System.out.println(firstStmt);
System.out.println(secondStmt);

It is important to note that relational expressions always result in a boolean value of true or false. For example given that varX = 3 and varY = 9, what would be the value of each of the following relational expressions?

  1. varX > 3
  2. varX > varY
  3. varX <= varY
  4. varY = 5
  1. varX > 3 is False
  2. varX > varY is False
  3. varX <= varY is True
  4. varY = 5 is actually an assignment statement, and we know 5 is an int.. so if varY is also an int, then this has a return type of int

Exercises

1. Which of the following are relational expressions in Java? For the items that aren't relational expressions, what kind of expressions/statements are they?

  1. x == 3
  2. x = 3
  3. x >= 3
  4. x * 3
  5. 3 < x
  6. x - 3 <= 10

2. Write a program that generates two random integers between 1 and 10 and store them into the variables value1 and value2.
There are a couple of ways to generate a random integer. One easy way is to use the Math.random():
int randomNum = (int)(Math.random() * 100) + 1;
The statement above will generate a random number between 1 and 100.
After generating two random numbers and storing them into variables, display a math quiz by asking the user what value1 + value2 is. Ask the user for their answer, and display whether their answer is "true" or "false". Sample user interaction is shown below (user input in purple):

What is 4 + 3?  7

4 + 3 = 7  is true

Another output example:

What is 2 + 1?  2

2 + 1 = 2  is false
  1. x == 3: relational expression
  2. x = 3: assignment statement
  3. x >= 3: relational expression
  4. x * 3: mathematical expression
  5. 3 < x: relational expression
  6. x - 3 <= 10: relational expression

2.

import java.util.Scanner;

public class MathQuestion {

    public static void main(String[] args) {

        // create a Scanner for keyboard input
        Scanner in = new Scanner(System.in);

        // generate two random numbers
        int value1 = (int)(Math.random() * 10) + 1;
        int value2 = (int)(Math.random() * 10) + 1;

        // display the question and get the user's answer
        System.out.printf("What is %d + %d?", value1, value2);
        int answer = in.nextInt();

        // calculate the real answer
        int realAnswer = value1 + value2;

        // determine if the user is correct
        boolean correct = realAnswer == answer;

        // display the user's result
        System.out.printf("%d + %d = %d is %B%n", value1, value2, answer, correct);
    }
}

Logical Operators

You can combine relational expressions into compound expressions using logical operators. For example, you might have asked the user for a department number, and you want to make sure that the number is between 1 and 10, inclusive. You might ask, "is the department number greater than or equal to 1, and less than or equal to 10?" There are two relational expressions in this statement: "deptNum >= 1" and "deptNum <= 10". In order for the number to be considered valid, both of these conditions have to be true; deptNum must be >= 1 AND deptNum must be <= 10. Notice that we have joined the two expressions using "AND" - both conditions must be true in order for the number to be valid. If one of the conditions is false, then the number is not valid and the entire expression would evaluate to false. This is how the AND operator functions.

You could also word the entire condition as expression asking if the number is invalid: "is the department number less than one or greater than 10?" In this case, your two relational expressions are "deptNum < 1" and "deptNum > 10". In this case, we would say that the number is invalid if deptNum is < 1 OR deptNum is > 10. If one of these conditions is true, then the entire statement is true and the number is invalid. The OR operator joins two expressions such that the entire statement will return true if one of the two conditions is true.

A third logical operator, NOT, is used to negate an expression. For example, I might want to ask if deptNum is a positive number. I could say "deptNum > 0" if I wanted, or I could say, "what if deptNum was NOT greater than 0?" In this case, I'd say "NOT(deptNum > 0)" (and yes, I could also say "deptNum <= 0"). Note the brackets around the expression: You have to evaluate deptNum > 0 first, then apply the NOT operator. Brackets are always first in the standard order of precedence. More on that in a moment.

The following table lists the symbols used for each of the logical operators in Java::

Logical Operators
Operator Symbol
AND &&
OR ||
NOT !

The expressions used above could all be written as:

deptNum >= 1 && deptNum <= 10
deptNum < 1 || deptNum > 10
!(deptNum > 0)

Note that there must be a complete expression on each side of the logical operator. In other words, the statement "deptNum >= 1 && <= 10" is invalid!

Logical operators have an order of precedence! Order of precedence for logical operators are () (brackets), NOT, AND, OR. Logical also have a lower precedence than many operators, but they have a higher precedence than the assignment operators.

Exercises

1. Given that a = 5, b = 2, c = 4, and d = 5, what is the result of each of the following Java expression?

  1. a == 5
  2. b * d == c * c
  3. d % b * c > 5 || c % b * d < 7
  4. d % b * c > 5 && c % b * d < 7

2. Given that:
a = 5
b = 2
c = 4
d = 6
e = 3
What is the result of each of the following relational expressions?

  1. a > b
  2. a != b
  3. d % b == c % b
  4. a * c != d * b
  5. d * b == c * e
  6. a * b < a % b * c
  7. c % b * a == b % c * a
  8. b % c * a != a * b
  9. d % b * c > 5 || c % b * d < 7
  10. d % b * c > 5 && c % b * d < 7

3. For each of the following statements, assign variable names for the unknowns and rewrite the statements as relational expressions.

  1. A customer's age is 65 or more.
  2. The temperature is less than 0 degrees.
  3. A person's height is over 6 feet.
  4. The current month is 12 (December).
  5. The user enters the name "Fred".
  6. The user enters the name "Fred" or "Wilma".
  7. The person's age is 65 or more and their sub total is more than $100.
  8. The current day is the 7th of the 4th month.
  9. A person is older than 55 or has been at the company for more than 25 years.
  10. A width of a wall is less than 4 metres but more than 3 metres.
  11. An employee's department number is less than 500 but greater than 1, and they've been at the company more than 25 years.

4. Determine the output the following program without running it:

public class Test {
    public static void main(String[] args) {
        char x = 'a';
        char y = 'c';
        System.out.println(++y);
        System.out.println(y++);
        System.out.println(x > y);
        System.out.println(x - y);
    }
}

5. for each code segment below, see if you can determine what the output would be. Then type the code into your editor and see if the actual output matches. If it doesn't match, why?

a)

int x = 1;
System.out.println((x >= 1) && (x++ > 1));
System.out.println(x);

b)

int x = 1;
System.out.println((x > 1) && (x++ > 1));
System.out.println(x);

6. Write a program that prompts the user for a whole number. Display if the number is positive or negative. Sample user interaction and output is shown below:

Enter a whole number: 3
Positive: true
Negative: false
Enter a whole number: -4
Positive: false
Negative: true

7. Write a program that asks a trivia question of your choice. The user enters the answer as a String. Compare their answer to the actual answer and display whether or not the user answered correctly. Sample user interaction and output is shown below (actual answers in my code were "James Gosling", "red", and the 3rd question had 2 answers "3" and "three"):

Who invented Java (first name and last name)?
james gosling
Correct? true
What is the background colour of the Ontario provincial flag?
green
Correct? false
How many territories are there in Canada?
3
Correct? true
How many territories are there in Canada?
three
Correct? true

1.

  1. a == 5 TRUE
  2. b * d == c * c
    = 2 * 5 == 4 * 4
    = 10 == 16 = FALSE
  3. d % b * c > 5 || c % b * d < 7
    = 5 % 2 * 4 > 5 || 4 % 2 * 5 < 7
    = 1 * 4 > 5 || 0 * 5 < 7
    = FALSE || TRUE = TRUE
  4. d % b * c > 5 && c % b * d < 7
    = 5 % 2 * 4 > 5 && 4 % 2 * 5 < 7
    = 1 * 4 > 5 && 0 * 5 < 7
    = FALSE && TRUE
    = FALSE

2. Given that:
a = 5
b = 2
c = 4
d = 6
e = 3
What is the result of each of the following relational expressions?

  1. a > b
    = 5 > 2
    = true
  2. a != b
    = 5 != 2
    = true
  3. d % b == c % b
    = 6 % 2 == 4 % 2
    = 0 == 0
    = true
  4. a * c != d * b
    = 5 * 4 != 6 * 2
    = 20 != 12
    = true
  5. d * b == c * e
    = 6 * 2 == 4 * 3
    = 12 == 12
    = true
  6. a * b < a % b * c
    = 5 * 2 < 5 % 2 * 4
    = 10 < 1 * 4
    = false
  7. c % b * a == b % c * a
    = 4 % 2 * 5 == 2 % 4 * 5
    = 0 * 5 == 2 * 5
    = false
  8. b % c * a != a * b
    = 2 % 4 * 5 != 5 * 2
    = 2 * 5 != 10
    = false
  9. d % b * c > 5 || c % b * d < 7
    = 6 % 2 * 4 > 5 || 4 % 2 * 6 < 7
    = 0 * 4 > 5 || 0 * 6 < 7
    = 0 > 5 || 0 < 7
    = true
  10. d % b * c > 5 && c % b * d < 7
    = 6 % 2 * 4 > 5 && 4 % 2 * 6 < 7
    = 0 * 4 > 5 && 0 * 6 < 7
    = 0 > 5 && 0 < 7
    = false

3.

  1. A customer's age is 65 or more: custAge >= 65
  2. The temperature is less than 0 degrees: temperature < 0
  3. A person's height is over 6 feet: hight > 6.0
  4. The current month is 12 (December): month == 12
  5. The user enters the name "Fred": userName.equals("Fred") or userName.equalsIgnoreCase("Fred")
  6. The user enters the name "Fred" or "Wilma"
    userName.equals("Fred") || userName.equals("Wilma") OR
    userName.equalsIgnoreCase("Fred") || userName.equalsIgnoreCase("Wilma")
  7. The person's age is 65 or more and their sub total is more than $100
    age >= 65 && subTotal > 100
  8. The current day is the 7th of the 4th month
    day == 7 && month == 4
  9. A person is older than 55 or has been at the company for more than 25 years
    age > 55 || numYears > 25
  10. A width of a wall is less than 4 metres but more than 3 metres
    width > 3 && width < 4
  11. An employee's department number is less than 500 but greater than 1, and they've been at the company more than 25 years
    deptNum < 500 && deptNum > 1 && numYears > 25

4.

d
d
false
-4

5.

a)
false
2
This is probably what you would expect to get: The entire expression evaluates to false, and x has a value of 2 after the statement executes: (x >= 1) is true, but (x > 1) is false, so the entire expression is false. After the evaluation of the conditions are complete, x increments by 1 and becomes 2.

b)
false
1
This may not be the output you expected: The expression evaluates to false, but notice that the value of x after this expression executes is 1. This is because of the short-circuiting of the Java && operator: Since the first condition (x > 1) is false, Java doesn't even bother checking the second condition, so therefore the x++ is never executed.

6.

Question 6. number is positive/negative

7.

Question 7. displaying trivia questions