๐Ÿ““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
  1. Go to the public template repository for our class: BWL-CS Java Template
  2. Click the button above the list of files then select Create a new repository
  3. Specify the repository name: CS2-Unit2PartA-Notes
  4. For the description, write: Selection/Conditionals (boolean expressions, if-else statements)
  5. Click

    Now you have your own personal copy of this starter code that you can always access under the Your repositories section of GitHub! ๐Ÿ“‚

  6. Now on your repository, click and select the Codespaces tab
  7. Click Create Codespace on main and wait for the environment to load, then youโ€™re ready to code!
  8. ๐Ÿ“ 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:

  1. Navigate to the Source Control menu on the LEFT sidebar
  2. Click the button on the LEFT menu
  3. Type a brief commit message at the top of the file that opens, for example: updated Main.java
  4. Click the small โœ”๏ธ checkmark in the TOP RIGHT corner
  5. Click the button on the LEFT menu
  6. Finally you can close your Codespace!

Boolean Variables & Expressions

  • Boolean variables are data containers of type boolean that can only store either true or false as values.
    • Example: boolean lightsOn = true;
  • Boolean expressions are statements with comparisons/tests that need to be evaluated, but will ultimately result in only true or false.
    • Example:
      boolean passing = (grade > 60);
      

      (grade > 60) is the boolean expression that evaluates to true if the value of the variable grade is greater than 60, or false otherwise. That result can be stored in a boolean variable like passing.

โ“ 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.

image

  • In the figure above, 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 point to the same object (same Turtle) 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 (int and double), but for reference/object types like String, 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 > 0 returns true
  • Test if a number is negative: number < 0 returns true
  • Use the remainder operator it to check for divisibility by 2:
    • If num % 2 != 0 is true โ†’ num is odd
    • If num % 2 == 0 is true โ†’ num is even
  • You can also use remainder to check if a number is a evenly divisible by any another number:
    • If num1 % num2 == 0 is true โ†’ num1 is a multiple of num2
  • 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 != 0 will be true if num is positive and odd and false when num is even, both of which are correct. HOWEVER if num is negative and odd, its remainder when divided by 2 is -1, not 1, and this expression will (incorrectly) evaluate to false.

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 Boolean value of true or false.
  • The remainder operator % can be used to test for divisibility by a number. For example, num % 2 == 0 can 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.