Day 4: Conditional Statements
Conditional statements are essential syntax for controlling program flow. They allow different code to be executed depending on specific conditions. Java provides two types of conditional statements: if-else and switch.
if-else Statement
The most basic conditional branch. The block executes when the condition evaluates to true.
public class IfElseExample {
public static void main(String[] args) {
int score = 85;
// Simple if
if (score >= 60) {
System.out.println("You passed!");
}
// if-else
if (score >= 90) {
System.out.println("Grade A");
} else {
System.out.println("Not grade A");
}
// if-else if-else (multiple branches)
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
// Nested if (prefer early return when possible)
boolean isMember = true;
int purchaseAmount = 50000;
if (isMember) {
if (purchaseAmount >= 30000) {
System.out.println("Member discount + free shipping");
} else {
System.out.println("Member discount only");
}
}
}
}
Combining Conditions with Logical Operators
Complex conditions can be combined using &&, ||, and ! operators.
public class CombinedCondition {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
boolean isDrunk = false;
// AND condition: all conditions must be met
if (age >= 18 && hasLicense && !isDrunk) {
System.out.println("You can drive.");
}
// OR condition: at least one must be met
String day = "Saturday";
if (day.equals("Saturday") || day.equals("Sunday")) {
System.out.println("It's the weekend! Take a rest.");
}
// Range check
int temperature = 24;
if (temperature >= 20 && temperature <= 28) {
System.out.println("The temperature is comfortable.");
}
// Concise with the ternary operator
String result = (age >= 18) ? "adult" : "minor";
System.out.println(result);
}
}
switch Statement
When branching based on a single variable’s value, switch is cleaner than if-else if.
public class SwitchExample {
public static void main(String[] args) {
// Traditional switch
int month = 4;
String monthName;
switch (month) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
default:
monthName = "Other";
break;
}
System.out.println("Current month: " + monthName);
// Grouping multiple values in a single case
switch (month) {
case 3: case 4: case 5:
System.out.println("It's spring");
break;
case 6: case 7: case 8:
System.out.println("It's summer");
break;
case 9: case 10: case 11:
System.out.println("It's autumn");
break;
case 12: case 1: case 2:
System.out.println("It's winter");
break;
}
}
}
Enhanced switch Expressions (Java 14+)
The arrow syntax introduced in Java 14 allows concise code without break.
public class EnhancedSwitch {
public static void main(String[] args) {
String grade = "B";
// Arrow syntax switch expression
String comment = switch (grade) {
case "A" -> "Excellent!";
case "B" -> "Well done!";
case "C" -> "Average.";
case "D" -> "Try harder.";
case "F" -> "You need to retake the course.";
default -> "Invalid grade.";
};
System.out.println(comment);
// Multiple value matching
int day = 3;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "weekday";
case 6, 7 -> "weekend";
default -> "invalid day";
};
System.out.println("Today is a " + type + ".");
// Using yield for complex logic
int score = 85;
String result = switch (score / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
default -> {
if (score >= 60) {
yield "D";
} else {
yield "F";
}
}
};
System.out.println("Grade: " + result);
}
}
Today’s Exercises
-
BMI Calculator: Store height (cm) and weight (kg) in variables, calculate the BMI, and classify it as “underweight” if below 18.5, “normal” if 18.5-24.9, “overweight” if 25-29.9, and “obese” if 30 or above. (BMI = weight / (height_m * height_m))
-
Day of Week Converter: Convert an integer (1-7) to a day name using a switch expression, and also print whether it is a weekday or weekend.
-
Amusement Park Pricing: Calculate the admission fee based on age and discount eligibility (boolean). Age 3 and under: free, age 4-12: 15,000 KRW, age 13-64: 30,000 KRW, age 65 and over: free. Apply a 50% discount for eligible guests.