π3.1: Booleans
Table of Contents
π This page is a condensed version of CSAwesome Topic 3.1
Using a GitHub Template for class notes
- 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-3-Notes
- Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositories
section of GitHub! - Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
and wait for the environment to load, then youβre ready to code! - π Take notes in this Codespace during class, coding along with the instructor.
Boolean Expressions
Boolean variables or expressions can only have true or false values.
Testing Equality ==
The operators ==
and !=
(not equal) can be used to compare values. They return true or false boolean values.
One =
sign changes the value of a variable. Two ==
equal signs are used to test if a variable holds a certain value, without changing its value!
Watch the following video which shows what happens in memory as primitive types like int
and reference types like Dog
are compared with ==
in a physical model of Java memory:
What will the code below print out? Try to guess before you run it! Note that 1 equal sign (=
) is used for assigning a value and 2 equal signs (==
) for testing values.
int age = 15;
int year = 14;
// Will this print true or false?
System.out.println(age == year);
year = 15;
// Will this print true or false?
System.out.println(age == year);
// Will this print true or false?
System.out.println(age != year);
We can also use ==
or !=
to test if two reference values, like Turtle
and String
objects, refer to the same object.
In the figure below, we are creating two separate Turtle
objects called juan
and mia
. They do NOT refer to same object or turtle! Then, we create a reference variable called friend
that is set to mia
. The turtle mia
will have two ways (references or aliases) to name her β sheβs both mia
and friend
, and these variables refer to the same object (same Turtle
) in memory. If two reference variables refer to the same object like the turtle on the right in the image below, the test with ==
will return true which you can see in the code below.
Relational Operators <
, >
The Relational Operators below in Java are used to compare numeric values or arithmetic expressions. Although some programming languages allow using relational operators like <
to compare strings, Java only uses these operators for numbers, and uses the methods compareTo
and equals
for comparing String
values.
Operator | Description |
---|---|
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
== | Equals |
!= | Does not equal |
π If you have trouble telling <
and >
apart, use the βhungry alligatorβ mnemonic beloved by elementary school teachersβ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 in English: βless than or equal toβ not βequal to or less thanβ.
Testing with remainder %
Here are some boolean expressions that are very useful in coding, and remainder is used in many of them:
// Test if a number is positive
(number > 0)
//Test if a number is negative
(number < 0)
//Test if a number is even by seeing if the remainder is 0 when divided by 2
(number % 2 == 0)
//Test if a number is odd by seeing if there is a remainder when divided by 2
(number % 2 > 0)
//Test if a number is a multiple of x (or divisible by x with no remainder)
(number % x == 0)
The remainder operator has been used quite a bit on the AP CSA exam, so you should be familiar with it.
-
Use it to check for odd or even numbers. If
num % 2 != 0
is true,num
is odd and ifnum % 2 == 0
is true thennum
is even. -
You can also use remainder to check if any number is evenly divisible by any other: If
num1 % num2 == 0
is true thennum1
is evenly divisible bynum2
. -
Use it to get the last digit from an integer number:
num % 10
gives us the rightmost digit ofnum
. -
Use it to get the number of minutes left when you convert a total number of minutes to hours and minutes:
int totalMinutes = 345;
int hours = totalMinutes / 60; // Number of whole hours, i.e. 5
int minutes = totalMinutes % 60; // Number of minutes left over, i.e. 45
- Use it whenever you have limit in the value, and you need to wrap around to zero if the value goes over the limit: the value of
num % limit
will always be in the range from 0 (inclusive) tolimit
(exclusive) as long asnum
andlimit
are both positive.
Because Javaβs %
is a remainder operator and not a true mathematical modulo operator (as we discussed briefly in section 1.4) you canβt check if a number is odd with the expression num % 2 == 1
.
That expression will be
true
ifnum
is positive and odd andfalse
whennum
is even, both of which are correct. But ifnum
is negative and odd, its remainder when divided by 2 is -1, not 1 and this expression will evaluate tofalse
. Thus you should always usenum % 2 != 0
to check ifnum
is odd.
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. We encourage you to work in pairs and see how high a score you can get.
βοΈ Summary
- Primitive values and reference values can be compared using relational operators (i.e.,
==
and!=
) in Java. - Arithmetic expression values can be compared using relational operators (i.e.,
<
,>
,<=
,>=
) in Java. - An expression involving relational operators evaluates to a
boolean
value of eithertrue
orfalse
.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.