Things To Do First

Things To Do Later

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 of 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, the Scanner class 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

Chapter 3.2 of your textbook goes over relational expressions. You may have already covered this material in Math class, so this could be a bit of review.

You've already learned about the mathematical operators, now it's time to learn about relational operators. Like many other kinds of operators, relational operators are binary operators: they require two operands. The relational operators used in Java can be found on in table 3.1 in Chapter 3.2.

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 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?

Exercises

[Solutions]

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

Comparing Strings

Comparing strings in Java is not as straightforward as it might seem at first. Strings are objects, so we shouldn't compare them with the == operator. With objects, comparing with == checks to see if two variables are "pointing to" the same object in memory. We will leave the explanation of this for a time when we start learning about classes and objects. For now you should know that it's considered bad programming to compare strings with ==. Instead, we use a special method called equals().

The equals() method is part of Java. It operates on a single string, and you pass a second string to it as an argument. The equals() method will then compare the two strings for equality. If the strings are the same, the method will return the boolean value true. If the strings are not equal, the method will return the boolean value false. For example:

String name = "Kaluha";
String userName = "Fred";
String beverage = "kaluha";

System.out.println(name.equals(userName));	// prints false
System.out.println(name.equals("Kaluha"));	// prints true
System.out.println(name.equals(beverage));	// prints false

In the first print statement, the string "Kaluha" is being compared to "Fred". These are not equal, so the result false is printed.

In the second print statement, the string "Kaluha" is being compared with the string "Kaluha". These are the same, so the result true is printed.

In the last print statement, the string "Kaluha" is not equal to "kaluha", so the result false is printed.

This last print statement brings up an important issue: what if you want a case-insensitive comparison? Use the equalsIgnoreCase() method instead! For example, the statement

System.out.println(name.equalsIgnoreCase(beverage));

will print the boolean result true!

Exercise

[Solution]

1. Write a program that asks the user for a name. Display the result of comparing the user-entered name to your own name.

Logical Operations

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 (also found in table 3.3 on page 93 of your textbook):

OperatorSymbol
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. Be sure to refer to your Order of Precedence chart in Appendix C.

Exercise

[Solutions]

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. Show the output of the following program:

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