Getting Started
In programming, we constantly need our applications to make decisions based on specific conditions. For a program to check if a user is old enough to register, if a password is correct, or if a game is over, it must evaluate whether a certain statement is true or false. This is achieved using boolean expressions, the fundamental building blocks of logic and control flow in Java.
What You Should Be Able to Do
Evaluate expressions that use relational operators (
<,==,!=, etc.) to compare values.Evaluate compound expressions that use logical operators (
!,&&,||) to combine boolean values.Apply De Morgan's Laws to write equivalent boolean expressions.
Trace the short-circuit evaluation of expressions using
&&and||.Distinguish between comparing primitive types with
==and comparing objects with.equals().
Key Concepts & Java Implementation
The Core Idea
A boolean expression is any statement that results in one of two values: true or false. These values belong to Java's boolean primitive data type. Think of a boolean expression as a question that can only be answered with "yes" (true) or "no" (false). For example, the expression score > 90 asks, "Is the value of score greater than 90?" The answer will be either true or false.
These expressions are the core of decision-making. They are used in control structures like if statements and loops to determine which block of code should execute next. We can create simple boolean expressions using relational operators (like >) and combine them into more complex ones using logical operators (like && for "and").
Syntax & Implementation
Relational Operators
Relational operators are used to compare two values. The result of a comparison is always a boolean value.
Syntax Table: Relational Operators
| Operator | Name | Java Example | Result if x is 10 |
|---|---|---|---|
== | Equal to | x == 10 | true |
!= | Not equal to | x != 5 | true |
> | Greater than | x > 5 | true |
< | Less than | x < 10 | false |
>= | Greater than or equal to | x >= 10 | true |
<= | Less than or equal to | x <= 9 | false |
// Annotated Java Example: Using Relational Operators
int score = 88;
double gpa = 3.5;
// These expressions evaluate to true or false
boolean isHighScore = score > 90; // isHighScore becomes false
boolean isPassing = score >= 65; // isPassing becomes true
boolean isPerfectGpa = gpa == 4.0; // isPerfectGpa becomes false
System.out.println("High Score? " + isHighScore);
System.out.println("Passing? " + isPassing);
Logical Operators
Logical operators combine or modify one or more boolean expressions to produce a single boolean result.
Syntax Table: Logical Operators
| Operator | Name | Java Example | Description |
|---|---|---|---|
! | NOT | !isTired | Inverts a boolean value. !true is false, and !false is true. |
&& | AND | isAwake && hasCoffee | Results in true only if both expressions are true. |
| ` | ` | OR |
// Annotated Java Example: Combining Operators
int age = 20;
boolean hasLicense = true;
// This expression checks if the person is a legal adult driver
boolean canRentCar = (age >= 25) && hasLicense; // (false && true) results in false
// This expression checks if a person gets a discount
boolean isStudent = true;
boolean isSenior = false;
boolean getsDiscount = isStudent || isSenior; // (true || false) results in true
// This expression uses the NOT operator
boolean isRaining = false;
boolean canGoToPark = !isRaining; // !false results in true
Tracing & Analysis
Short-Circuit Evaluation
Java uses short-circuit evaluation for && and || operators for efficiency.
For an
&&(AND) expression, if the first part isfalse, the entire expression must befalse. Java will not evaluate the second part.For an
||(OR) expression, if the first part istrue, the entire expression must betrue. Java will not evaluate the second part.
This is not just for speed; it's crucial for preventing errors, like dividing by zero.
Execution Trace:
Consider the following code:
int students = 0;
int totalScore = 100;
// We want to check if the average score is above 20
// If students is 0, the second part of the && is never run.
if (students != 0 && (totalScore / students) > 20) {
System.out.println("High average score.");
} else {
System.out.println("Not enough data or low average.");
}
students != 0is evaluated. Sincestudentsis0, this isfalse.Because the operator is
&&and the first part isfalse, the entire expression must befalse.Java short-circuits and does not evaluate
(totalScore / students) > 20.This prevents a runtime error, as
100 / 0would crash the program. Theelseblock executes.
De Morgan's Laws
De Morgan's Laws are rules that show how to distribute a negation (!) operator inside a compound boolean expression. They are useful for simplifying complex logic.
!(a && b)is equivalent to!a || !b!(a || b)is equivalent to!a && !b
In words: "not (a and b)" is the same as "(not a) or (not b)". And "not (a or b)" is the same as "(not a) and (not b)".
// Analysis: De Morgan's Laws
boolean hasTime = false;
boolean hasEnergy = false;
// Original statement: It's NOT the case that I have time AND energy.
boolean cannotGoOut = !(hasTime && hasEnergy); // !(false && false) -> !false -> true
// Equivalent statement using De Morgan's Law:
// I do NOT have time OR I do NOT have energy.
boolean cannotGoOutEquivalent = !hasTime || !hasEnergy; // !false || !false -> true || true -> true
// Both expressions yield the same result.
Java Syntax Quick-Reference
| Operator/Method | Purpose |
|---|---|
== | Returns true if two primitive values are equal or two references point to the same object. |
!= | Returns true if two values/references are not equal. |
>, <, >=, <= | Relational operators for comparing numeric or character values. |
! | Logical NOT. Inverts a boolean value. |
&& | Logical AND. Returns true only if both operands are true. |
| ` | |
.equals(Object o) | A method used to compare the contents of two objects for equality. |
Core Code Examples & Terminology
boolean: A primitive data type in Java that can only hold one of two values:trueorfalse.Boolean Expression: An expression that evaluates to a
booleanvalue (trueorfalse).Relational Operators: A set of operators including
==,!=,>,<,>=, and<=that compare two operands and produce abooleanresult.Logical Operators: The operators
!,&&, and||, which perform logical NOT, AND, and OR operations on boolean values.Short-Circuit Evaluation: The process where the second operand of a logical expression (
&&or||) is only evaluated if the first operand is not sufficient to determine the final result.Core Snippet 1 (Compound Expression):
boolean canVote = (age >= 18) && isCitizen;This line determines voting eligibility by checking if two separate conditions are both
true.Core Snippet 2 (Object Comparison):
String a = new String("hi"); String b = new String("hi"); boolean areSameObject = (a == b); // false boolean haveSameContent = a.equals(b); // trueThis demonstrates that
==checks if two references point to the same memory location, while.equals()checks if the objects' contents are meaningfully the same.Core Snippet 3 (De Morgan's Law Application):
// !(isRaining || isCold) is equivalent to !isRaining && !isColdThis shows how to simplify a negated OR condition into an AND condition with negated parts.
Core Skill Check
Code Tracing: What is the final value of
canGoafter this Java code runs:int temp = 75; boolean isSunny = true; boolean canGo = isSunny && (temp > 80);?Debugging: Identify the logical error in this Java code intended to check if two
Stringobjects have the same text:String pass1 = "java123"; String pass2 = new String("java123"); if (pass1 == pass2) { /* grant access */ }.Application: Write a single line of Java to declare a
booleanvariableisInvalidthat istrueif anintvariablenumis less than 0 or greater than 100.
Common Misconceptions & Errors
Using
=instead of==: A single equals sign (=) is for assignment, not comparison.if (x = 5)assigns 5 toxand causes an error, whereasif (x == 5)correctly checks ifxis equal to 5.Using
==to Compare Objects: For objects likeString,==checks if two variables refer to the exact same object in memory, not if their contents are the same. Always use the.equals()method for checking content equality of objects.Incorrectly Applying De Morgan's Laws: When negating an expression like
!(a && b), a common mistake is to write!a && !b. The correct transformation requires flipping the operator:!a || !b.Forgetting Operator Precedence:
&&has a higher precedence than||. The expressiontrue || false && falseevaluates totruebecause the&&is performed first (false && falseisfalse), leavingtrue || false. Use parentheses()to ensure the desired order of evaluation.
Summary
Boolean expressions are the cornerstone of logic in Java, allowing programs to make decisions and control their flow. Every boolean expression evaluates to either true or false. Relational operators (==, >, etc.) are used to compare values, forming simple boolean expressions. These can be combined into more complex conditions using logical operators (&&, ||, !). Understanding concepts like short-circuit evaluation is key to writing efficient and error-free code. Finally, the distinction between comparing primitives with == and comparing objects with the .equals() method is a critical concept in object-oriented programming.