Unit 3: Boolean Expressions and if Statements
This unit introduces Boolean logic, conditional statements, and decision-making in Java.
Key Concepts
- Boolean Expressions: Expressions that evaluate to
true
orfalse
. - Relational Operators:
==
,!=
,<
,>
,<=
,>=
. - Logical Operators:
&&
(AND),||
(OR),!
(NOT). - Conditional Statements:
if
,else if
,else
. - Nested Conditionals: Using conditionals inside other conditionals.
- De Morgan's Laws: Rules for simplifying logical expressions.
Example Code: Basic Boolean Expressions
// Example: Boolean Expressions and if Statements
public class BooleanExample {
public static void main(String[] args) {
int age = 18;
boolean isStudent = true;
// Boolean expression with relational and logical operators
if (age >= 18 && isStudent) {
System.out.println("You are an adult student.");
} else if (age >= 18 || isStudent) {
System.out.println("You are either an adult or a student.");
} else {
System.out.println("You are neither an adult nor a student.");
}
// Nested conditionals
if (age > 16) {
if (isStudent) {
System.out.println("You are a student above 16.");
} else {
System.out.println("You are above 16 but not a student.");
}
}
}
}
Example Code: Advanced Boolean Expressions
// Example: Advanced Boolean Expressions and Complex Conditionals
public class AdvancedBooleanExample {
public static void main(String[] args) {
// Complex boolean expressions
int score = 85;
boolean isPassing = score >= 60;
boolean isHonors = score >= 90;
boolean hasPerfectAttendance = true;
// Using De Morgan's Laws
boolean notPassing = !isPassing;
boolean notHonors = !isHonors;
// Complex conditional logic
if (isHonors && hasPerfectAttendance) {
System.out.println("Student qualifies for highest honors!");
} else if (isPassing && hasPerfectAttendance) {
System.out.println("Student qualifies for attendance award.");
} else if (isPassing) {
System.out.println("Student is passing.");
} else {
System.out.println("Student needs improvement.");
}
// Ternary operator example
String grade = isHonors ? "A" : (isPassing ? "C" : "F");
// Short-circuit evaluation
boolean result = isPassing || (score > 100); // Second condition never evaluated if isPassing is true
// Print results
System.out.println("Grade: " + grade);
System.out.println("Short-circuit result: " + result);
}
}
Boolean Expressions and Logical Operators
Common Boolean Operators:
Operator | Description | Example |
---|---|---|
&& |
Logical AND | true && false → false |
|| |
Logical OR | true || false → true |
! |
Logical NOT | !true → false |
== |
Equality | 5 == 5 → true |
!= |
Not equal | 5 != 3 → true |
Boolean Expression Examples:
// Basic boolean expressions
boolean isAdult = age >= 18;
boolean isTeenager = age >= 13 && age <= 19;
boolean isChild = age < 13;
// Complex boolean expressions
boolean canVote = age >= 18 && isCitizen;
boolean canDrive = age >= 16 || hasSpecialPermit;
boolean isWeekend = day == "Saturday" || day == "Sunday";
// Using NOT operator
boolean isNotAdult = !isAdult;
boolean isNotWeekend = !isWeekend;
Short-Circuit Evaluation:
// && short-circuits if first condition is false
if (x != 0 && y / x > 2) {
// Safe division because x != 0 is checked first
}
// || short-circuits if first condition is true
if (name == null || name.length() == 0) {
// Safe length check because null is checked first
}
Boolean Expression Tips:
- Use parentheses to clarify complex expressions
- Take advantage of short-circuit evaluation
- Use meaningful variable names for boolean values
- Consider De Morgan's Laws for simplifying expressions
- Be careful with floating-point comparisons
Common Pitfalls and Debugging Tips
Common Mistakes:
- Assignment vs. Comparison: Using = instead of ==
if (x = 5) { // Wrong! Assigns 5 to x if (x == 5) { // Correct! Compares x with 5
- Floating-Point Comparison: Using == with doubles
double x = 0.1 + 0.2; if (x == 0.3) { // Wrong! Might be false due to precision if (Math.abs(x - 0.3) < 0.0001) { // Correct! Uses tolerance
- String Comparison: Using == instead of equals()
String s1 = "Hello"; String s2 = new String("Hello"); if (s1 == s2) { // Wrong! Compares references if (s1.equals(s2)) { // Correct! Compares content
Debugging Tips:
- Use System.out.println() to print boolean values
- Break complex expressions into smaller parts
- Use parentheses to clarify operator precedence
- Test edge cases (null, zero, empty strings)
- Use truth tables to verify complex logic
AP Exam Tips:
- Know operator precedence rules
- Understand short-circuit evaluation
- Be able to evaluate complex boolean expressions
- Know when to use equals() vs ==
- Understand De Morgan's Laws
AP Exam-Style Practice Problems
Problem 1: Boolean Expression Evaluation
Consider the following code segment:
int x = 5;
int y = 10;
boolean result = (x > 3) && (y < 15) || (x + y == 20);
System.out.println(result);
What is printed as a result of executing the code segment?
Problem 2: Short-Circuit Evaluation
Consider the following code segment:
int x = 0;
boolean result = (x != 0) && (10 / x > 2);
System.out.println(result);
What is printed as a result of executing the code segment?
Problem 3: String Comparison
Consider the following code segment:
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
What is printed as a result of executing the code segment?
Problem 4: Complex Boolean Expression
Consider the following code segment:
int age = 16;
boolean hasLicense = true;
boolean hasParent = false;
boolean canDrive = (age >= 16 && hasLicense) || (age >= 15 && hasParent);
System.out.println(canDrive);
What is printed as a result of executing the code segment?
Multiple Choice Practice
Question 1:
What is the output of the following code?
int x = 5;
int y = 10;
System.out.println(x > 3 && y < 20);
Question 2:
Which of the following is true about logical operators in Java?
Question 3:
What is the result of the following code?
boolean a = true;
boolean b = false;
boolean c = true;
System.out.println(a && b || c);
Question 4:
Which of the following is NOT a valid boolean expression in Java?
Question 5:
What is the value of the following expression?
!(true && false) || (true && true)
Practice Problems
- Write a program that checks if a number is positive, negative, or zero.
- Write a program that determines if a year is a leap year.
- Write a program that checks if a user is eligible to vote (age >= 18).
- Write a program that uses nested conditionals to determine the grade based on a score.
- Write a program that checks if a number is divisible by both 3 and 5.
- Create a program that determines if a triangle is valid based on its side lengths.
- Write a program that checks if a string is a palindrome using boolean expressions.
- Create a program that determines if a number is prime using boolean logic.
Tips for Success
- Understand the difference between relational and logical operators.
- Practice writing and evaluating Boolean expressions.
- Use parentheses to clarify the order of operations in complex expressions.
- Test your conditionals with different inputs to ensure they work as expected.
- Learn De Morgan's Laws to simplify logical expressions.
- Be careful with the order of operations in complex boolean expressions.
- Use meaningful variable names for boolean values (e.g., isPassing, hasPermission).
- Remember that && has higher precedence than ||.
Interactive Code Playground
Try out your own boolean expressions and conditional statements here!
Output:
Note: This is a simulated environment. For actual Java code execution, please use an IDE or online Java compiler.
For actual code execution, we recommend using: