Basic if-else
java
if (condition) {
// runs when condition is TRUE
} else {
// runs when condition is FALSE
}
java
int age = 15;
if (age >= 16) {
System.out.println("Can drive");
} else {
System.out.println("Too young to drive");
}
// Output: Too young to drive
Why if-else instead of two if statements?
java
// Problem: Two independent if statements
int score = 85;
if (score >= 80) {
System.out.println("Good"); // prints
}
if (score < 80) {
System.out.println("Needs work");
}
java
// Better: if-else
int score = 85;
if (score >= 80) {
System.out.println("Good"); // prints
} else {
System.out.println("Needs work");
}
Tracing if-else statements
java
int x = 7;
String result;
if (x % 2 == 0) {
result = "even";
} else {
result = "odd";
}
System.out.println(x + " is " + result);
Nested if-else
java
int score = 85;
boolean extraCredit = true;
if (score >= 90) {
System.out.println("A");
} else {
if (extraCredit) {
System.out.println("B+");
} else {
System.out.println("B");
}
}
// Output: B+
Trace the nested logic:
score = 85, extraCredit = true
1. Check: score >= 90? → 85 >= 90? → false → go to else
2. Check: extraCredit? → true → print "B+"
if-else with return values
java
public static String getGrade(int score) {
if (score >= 60) {
return "Pass";
} else {
return "Fail";
}
}
System.out.println(getGrade(75)); // "Pass"
System.out.println(getGrade(45)); // "Fail"
One-line if-else (ternary operator)
java
// Full if-else
String status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
// Ternary shorthand
String status = (age >= 18) ? "adult" : "minor";
java
int max = (a > b) ? a : b; // maximum of two numbers
String sign = (x >= 0) ? "positive" : "negative";
int abs = (x >= 0) ? x : -x; // absolute value
Complete example: Movie ticket pricing
java
public class TicketPrice {
public static void main(String[] args) {
int age = 14;
boolean isMatinee = true;
double price;
if (age < 12) {
price = 8.00;
} else {
price = 12.00;
}
// Apply matinee discount
if (isMatinee) {
price -= 2.00;
}
System.out.println("Ticket: $" + price);
}
}
AP Exam Tips
- •
- •
- •
- •
- •