Basic if statement
java
if (condition) {
// code runs ONLY if condition is true
}
java
int score = 85;
if (score >= 70) {
System.out.println("You passed!");
}
// Output: You passed!
java
int score = 50;
if (score >= 70) {
System.out.println("You passed!"); // skipped
}
System.out.println("Done"); // always runs
// Output: Done
How conditions work
java
int age = 16;
if (age >= 16) { // 16 >= 16 → true → runs
System.out.println("Can drive");
}
if (age >= 18) { // 16 >= 18 → false → skipped
System.out.println("Can vote");
}
Comparison operators in conditions
Multiple if statements
java
int temp = 75;
if (temp > 90) {
System.out.println("Hot");
}
if (temp > 60) {
System.out.println("Warm"); // prints
}
if (temp > 32) {
System.out.println("Above freezing"); // prints
}
Tracing if statements
java
int x = 4;
int result = 0;
if (x > 0) {
result += x; // result = 4
}
if (x > 3) {
result *= 2; // result = 8
}
if (x > 5) {
result += 10; // skipped
}
System.out.println(result);
Curly braces matter
java
int x = 3;
if (x > 10)
System.out.println("A"); // controlled by if — skipped
System.out.println("B"); // NOT controlled by if — always runs!
java
// Good — clear and safe
if (x > 10) {
System.out.println("A");
}
Comparing objects with if
java
String name = "Alice";
// CORRECT
if (name.equals("Alice")) {
System.out.println("Found Alice!");
}
// WRONG — compares references, not content
if (name == "Alice") {
// This might work sometimes but is unreliable!
}
Complete example: Grade checker
java
public class GradeChecker {
public static void main(String[] args) {
int score = 87;
String message = "";
if (score >= 90) {
message = "Excellent!";
}
if (score >= 80) {
message = "Good job!";
}
if (score >= 70) {
message = "Passing";
}
System.out.println(message); // "Passing"
}
}
AP Exam Tips
- •
- •
- •
- •
- •