Boolean expressions review
java
int x = 10;
x > 5 // true
x == 10 // true
x != 10 // false
x < 0 // false
x >= 10 // true
x <= 9 // false
Relational operators
The if statement
java
int temperature = 95;
if (temperature > 90) {
System.out.println("It's hot outside!");
}
// Output: It's hot outside!
java
int temperature = 72;
if (temperature > 90) {
System.out.println("It's hot outside!"); // skipped
}
// No output
Syntax breakdown
java
if (condition) { // condition must be a boolean expression
// code to run // only runs if condition is true
} // curly braces define the block
Multiple if statements vs. if-else
java
int score = 95;
if (score >= 90) {
System.out.println("A"); // prints
}
if (score >= 80) {
System.out.println("B"); // ALSO prints!
}
if (score >= 70) {
System.out.println("C"); // ALSO prints!
}
// Output: A B C (all three!)
Scope of variables in if blocks
java
if (true) {
int x = 10; // x exists only here
System.out.println(x); // works
}
// System.out.println(x); // COMPILE ERROR — x doesn't exist here
java
int x = 10;
if (x > 5) {
x = 20; // modifying x from outer scope — works
}
System.out.println(x); // 20
Single-statement if (no braces)
java
// Legal but dangerous:
if (x > 0)
System.out.println("positive");
// TRAP — this is NOT part of the if:
if (x > 0)
System.out.println("positive");
System.out.println("done"); // ALWAYS runs! (not inside the if)
Trace practice
java
int a = 15;
int b = 20;
int c = 15;
if (a == c) {
System.out.print("X");
}
if (a > b) {
System.out.print("Y");
}
if (b > a) {
System.out.print("Z");
}
AP Exam Tips
- •
- •
- •
- •
Common Mistakes
- •
- •
- •
- •