AP Computer Science A - Unit 3 Review: Boolean Expressions and Conditional Statements
true
or false
.if
statement.java
if (3 > 2) {
// Executes because expression is true
}
Used to compare two values:
==
: equals (used with primitive types)
!=
: not equal>
: greater than<
: less than>=
: greater than or equal to<=
: less than or equal toImportant:
==
is not the same as =
(assignment).
==
is only for primitives. Use .equals()
for object comparisons.Combine boolean expressions:
&&
: AND (both must be true)
||
: OR (either can be true)Short-Circuiting:
In &&
, if the first condition is false, the second is not evaluated.
||
, if the first condition is true, the second is not evaluated.java
if (condition) {
// Executes if condition is true
} else if (anotherCondition) {
// Executes if above is false and this is true
} else {
// Executes if all above are false
}
* Rules:
if
and else if
need a boolean expression.else
does not take a boolean expression.if-else if-else
chain.int x = 5;
if (x < 10) {
System.out.println("A"); // Runs
}
if (x < 4) {
System.out.println("B"); // Skipped
}
if (x < 7) {
System.out.println("C"); // Runs
}
if-else
structures inside one another.int x = 5, y = 3;
if (x < 10) {
if (y != 3) {
System.out.println("A");
} else if (y <= 5) {
System.out.println("B"); // Runs
} else {
System.out.println("C");
}
} else {
if (y < 2) {
System.out.println("D");
} else if (y == 3) {
System.out.println("E");
}
}
Semicolon after if
, else if
, or else
:
Breaks the structure; block executes regardless.
Adding condition to else
:
Invalid: else (x < 5)
→ causes a compile error.
Multiple statements without curly braces:
Only the first statement is considered inside the if
.
{}
for clarity and correctness.{}
can be omitted.if (x > 5)
System.out.println("X is large");
Summary:
Practice writing and tracing if-else
structures to prepare for AP CSA exam questions!