๐2.2: Boolean Expressions
Table of Contents
๐ This page is a condensed version of CSAwesome Topic 2.2
โดโดโด NEW UNIT/SECTION! โดโดโด
Create a blank Java program to take your class notes in for the next few lessons.
Click on the collapsed heading below for GitHub instructions โคต
๐ NOTES PROGRAM SETUP INSTRUCTIONS
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository - Specify the repository name:
CS2-Unit-2-A-Notes - For the description, write:
Selection/Conditionals (boolean expressions, if-else statements) - Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositoriessection of GitHub! ๐ - Now on your repository, click and select the
Codespacestab - Click
Create Codespace on mainand wait for the environment to load, then youโre ready to code! - ๐ Take notes in this Codespace during class, writing code & comments along with the instructor.
๐ When class ends, donโt forget to SAVE YOUR WORK! Codespaces are TEMPORARY editing environments, so you need to COMMIT changes properly in order to update the main repository for your program.
There are multiple steps to saving in GitHub Codespaces:
- Navigate to the
Source Controlmenu on the LEFT sidebar - Click the button on the LEFT menu
- Type a brief commit message at the top of the file that opens, for example:
updated Main.java - Click the small
โ๏ธcheckmark in the TOP RIGHT corner - Click the button on the LEFT menu
- Finally you can close your Codespace!
Boolean Variables & Expressions
- Boolean variables are data containers of type
booleanthat can only store eithertrueorfalseas values.- Example:
boolean lightsOn = true;
- Example:
- Boolean expressions are statements with comparisons/tests that need to be evaluated, but will ultimately result in only
trueorfalse.- Example:
boolean passing = (grade > 60);(grade > 60)is the boolean expression that evaluates totrueif the value of the variablegradeis greater than 60, orfalseotherwise. That result can be stored in a boolean variable likepassing.
- Example:
โ Boolean expressions are like simple questions where โyes or noโ are the only possible responses.
Testing Equality ==, !=
The relational operators == (equal) and != (not equal) can be used to compare two values. Expressions that include relational operators are evaluated and return a true or false boolean value.
The assignment operator, ONE = sign, changes the value of a variable. The equality operator, TWO == equal signs, are used to test if a variable holds a certain value, without changing its value!
๐ฎ Predict: What will the code below print out? Try to guess before you run it! Then, add a line of code that re-assigns the yourAge variable to 17, and print the boolean expression for whether yourAge is equals drivingAge.
int yourAge = 15;
int drivingAge = 17;
// 1. Will these print true or false?
System.out.println(yourAge == drivingAge);
System.out.println(yourAge != drivingAge);
// 2. Set yourAge to a new value of 17
// 3. Print whether yourAge equals drivingAge
Comparing Primitives vs. References
Watch the following video which shows what happens in memory as primitive data types like int and reference (object) types like Dog are compared with == in a physical model of Java memory:
So, we can also use == or != to test if two reference values, like Turtle and String objects, refer to the exact same object stored in memory.

- In the figure above, we are creating two separate
Turtleobjects calledjuanandmia. They do NOT refer to same object or turtle!- Then, we create a reference variable called
friendthat is set tomia. The turtlemiawill have two ways (references or aliases) to name her โ sheโs bothmiaandfriend, and these variables point to the same object (sameTurtle) in memory.
Relational Operators <, <=, >, >=
The relational operators below in Java are used to compare numeric values or arithmetic expressions:
| Operator | Description |
|---|---|
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
== | Equals |
!= | Does not equal |
Java only allows these operators to be used with primitive type numbers (
intanddouble), but for reference/object types likeString, uses the methods.compareTo()and.equals().
๐ If you have trouble telling < and > apart, use the โhungry alligatorโ mnemonic: think of < and > as the mouths of hungry alligators which always want to eat the bigger number. A < or > expression is only true if the alligator is in fact about to eat the bigger number.
To remember the correct order of the two characters in <= and >=, just write them in the same order you would say them out loud in English: โless than or equal toโ not โequal to or less thanโ.
๐ฎ Predict: What will the value of result be after execution?
boolean result = (5 % 3 == 0) != (3 > 5);
Testing with Remainder %
Here are some common boolean expressions that are very useful in coding, noting that the remainder operator (%) is used in many of them:
- Test if a number is positive:
number > 0returns true - Test if a number is negative:
number < 0returns true - Use the remainder operator it to check for divisibility by 2:
- If
num % 2 != 0is true โnumis odd - If
num % 2 == 0is true โnumis even
- If
- You can also use remainder to check if a number is a evenly divisible by any another number:
- If
num1 % num2 == 0is true โnum1is a multiple ofnum2
- If
- Use it to get the last digit from an integer number:
int digit = num % 10; - Use it to get the number of minutes left over when you convert a total number of minutes to hours and minutes:
int totalMins = 345; int hrs = totalMins / 60; // Number of whole hours int mins = totalMins % 60; // Number of mins left over
Because Javaโs % is a remainder operator, not a true modulo operator, you should always use num % 2 != 0 to check if a number is odd. You cannot accurately check if a number is odd with the expression num % 2 == 1.
That expression breaks with negative numbers.
num % 2 != 0will betrueifnumis positive and odd andfalsewhennumis even, both of which are correct. HOWEVER ifnumis negative and odd, its remainder when divided by 2 is -1, not 1, and this expression will (incorrectly) evaluate tofalse.
Relational Operators Game
๐ฒ Try the game below to practice! Click on Relationals, evaluate the relational expression and click on None, All, or the numbers that make the expression true. Check on Compound for an added challenge.
Summary
- (AP 2.2.A.1) Values or expressions can be compared using the relational operators
==and!=to determine whether the values are the same. With primitive types, this compares the actual primitive values. With reference types, this compares the object references. - (AP 2.2.A.2) Numeric values or expressions can be compared using the relational operators (
<,>,<=,>=) to determine the relationship between the values. - (AP 2.2.A.3) An expression involving relational operators evaluates to a
Booleanvalue oftrueorfalse. - The remainder operator
%can be used to test for divisibility by a number. For example,num % 2 == 0can be used to test if a number is even.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.