Skip to content

Latest commit

 

History

History
230 lines (166 loc) · 7.87 KB

File metadata and controls

230 lines (166 loc) · 7.87 KB

Boolean Expressions

When starting out in programming, the idea of a boolean variable, something that is either just true or false, seems like an overly simple thing…​ something that feels rather useless.

In fact, booleans in computer code are everywhere. They are simple, but also useful in many ways. You’ve probably heard about how everything in computers is ones and zeros at the lowest level - and that’s true. But on this super simple base of 0 and 1 is built all of the power of the internet, and all the apps you’ve ever used.

When you are coding, you often have to make a choice about what to do next based on some kind of condition or to do something repetitively (over and over) based on some condition. Something like is there gas in the car? or are we moving faster than 100mph? In real life, these are considered to be YES (or true) or NO (or false) kinds of questions. If the gas tank is empty, the question results in a FALSE condition. If there is some gas in the tank, then the question’s result is TRUE, "yes, there is some gas in the tank."

And while this may seem super simple to you, and it is, it is also very powerful when used in a program.

This idea of a condition that is either TRUE or FALSE, is known as a boolean expression. And in Java, they crop up everywhere. They are in conditional statements and they are part of loops.

Boolean expressions can be very complex, or very simple:

playerOne.isAlive() == true

might be a key thing to know inside of a game. But it might be more complicated:

player[1].isAlive() == true
&&
player[2].isAlive() == true
&&
spaceStation.hasAir() == true

(here, && means and)

All three things need to be true to continue the game. Using boolean expressions, we can build very powerful tests to make sure everything is just as we need it to be.

We also need more kinds of boolean expressions when we are programming. Things like less than or greater than or equal to, and other comparison operators so we can compare things to work out the relationships within our data.

Comparison Operators

int healthScore = 5;

We need a way to ask about expressions like "is healthScore less than 7?? (very healthy)" or "is healthScore greater than or equal to 3?? (maybe barely alive?)"

To do that we need a bunch of comparison operators.

Operator Description Example

==

Equal to

x == 5

!=

Not equal to

x != 55

>

Greater than

x > 1

<

Less than

x < 10

>=

Greater than or equal to

x >= 5

<=

Less than or equal to

x <= 5

Each of these can be used to make it very clear to someone reading your code what you meant. Imagine a flight simulator, where you’re flying a big, old fashioned airplane. The code that keeps track of the status of the plane might need to be able to make decisions on boolean expressions like:

altitude > 500.0   // high enough to not hit any trees!
airspeed >= 85.0   // fast enough to stay in the air.

fuelAvailable <= 5.0   // need to land to refuel!

totalCargoWeight < 6.0  // more than 6 tons and we can't take off!

pilot.isAlive() && copilot.isAlive()  // both are alive, keep flying.

In Java, ` == ` is used for equals in numbers (both int and double AND boolean). But when we compare two Stings, we use .equals(), like this player1name.equals("Roberto"). In Java you almost never want to use player1name == "Roberto", always use .equals() instead.

Like the && (and) in the examples above or this last boolean expression with the "&&" in it, we have in Java the ability to combine expressions into larger more complex expressions using && (and) and || (or).

Logical Operators

The logical operators are AND and OR, except in Java we use && for AND and || for OR.

Operator Description

&&

Logical AND

playerOneStatus == 'alive' && spacecraft.hasAir()

||

Logical OR

room.Temp > 70 || room.Temp < 75

The AND operator, '&&', is an operator where BOTH sides have to be true for the expression to be true.

(5 < 9) && (6-3 == 3)  // true

See how both expressions on either side of the '&&' are true? That makes the entire line true.

The OR operator, '||' [1], is an operator where if ONE or the OTHER or BOTH boolean expressions are true, the entire expression is true.

(5 < 9) || (6-3 == 3) // true

(5 == 4) || (7 > 3)   // true!

(5 == 4) || (6 == 2) // false (both are false)

Both sides of a logical operator need to be Boolean expressions. So it’s all right to use lots of different comparisons, and combine them with && and ||.

// deep in a cash machine application...
(customer.balance() <= 20.00
&&
customer.hasOverDraftProtection() == true)
||
(customer.savings.balance() > 20.0
&&
customer.canTransferFromSavings() )

See how these conditions could line up to allow a customer to get cash from the cash machine? Again, this is why boolean expressions are important and powerful and why coders need to be able to use them to get the software just right.

Exercise: Boolean Comparisons

  • Create 2 variables to use for a comparison

  • Use at least two comparison operators in Java

  • And print them "System.out.println(2 > 1)"

Here is an example:

double houseTemp = 67.0;
double thermostatSetting = 70.0;

System.out.println(houseTemp >= 55.0);
System.out.println(houseTemp <= thermostatSetting);
System.out.println(thermostatSetting != 72.0);
System.out.println(houseTemp > 65.0 && thermostatSetting == 68.0);

These log statements should produce TRUE, TRUE, TRUE and FALSE.

Chapter Exercises

Try these exercises in jshell to practice boolean expressions and logical operators:

Exercise 1: Basic Comparisons

Practice comparison operators:

int age = 22;
int votingAge = 18;
int drinkingAge = 21;

System.out.println("Age: " + age);
System.out.println("Can vote: " + (age >= votingAge));
System.out.println("Can drink: " + (age >= drinkingAge));
System.out.println("Is exactly voting age: " + (age == votingAge));
System.out.println("Is not drinking age: " + (age != drinkingAge));

Exercise 2: Logical AND and OR

Combine conditions with && and ||:

int temperature = 75;
boolean isSunny = true;
boolean hasUmbrella = false;

boolean perfectWeather = (temperature > 70) && isSunny;
boolean needJacket = (temperature < 60) || (!isSunny);
boolean goOutside = perfectWeather || (hasUmbrella && !isSunny);

System.out.println("Temperature: " + temperature + "°F, Sunny: " + isSunny);
System.out.println("Perfect weather: " + perfectWeather);
System.out.println("Need jacket: " + needJacket);
System.out.println("Go outside: " + goOutside);

Exercise 3: String Comparisons

Practice with string equality:

String password = "secret123";
String userInput = "secret123";
String wrongInput = "Secret123";

boolean correctPassword = password.equals(userInput);
boolean incorrectPassword = password.equals(wrongInput);
boolean isEmpty = password.equals("");

System.out.println("Correct password: " + correctPassword);
System.out.println("Incorrect password: " + incorrectPassword);
System.out.println("Password is empty: " + isEmpty);
System.out.println("Password length > 5: " + (password.length() > 5));

Exercise 4: Complex Conditions

Create a grade evaluation system:

int score = 85;
boolean hasExtraCredit = true;
boolean attendedAllClasses = true;

boolean passingGrade = score >= 70;
boolean excellentGrade = score >= 90;
boolean bonusEligible = hasExtraCredit && attendedAllClasses;
boolean finalPass = passingGrade || (score >= 60 && bonusEligible);

System.out.println("Score: " + score);
System.out.println("Passing grade: " + passingGrade);
System.out.println("Excellent grade: " + excellentGrade);
System.out.println("Bonus eligible: " + bonusEligible);
System.out.println("Final pass: " + finalPass);

1. shift-backslash '\' on most keyboards