Module 2: Java Fundamentals
Conditional Statements
Control program decisions with if, else, and switch.
Conditional statements choose which code to execute based on a boolean condition. They help a program respond to different inputs and situations.
if and else#
int score = 76;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 70) {
System.out.println("Grade B");
} else {
System.out.println("Keep practising");
}
Java tests conditions from top to bottom. Once a branch matches, its block runs and the remaining branches are skipped. Put more specific or higher-threshold conditions first when order matters.
switch#
A switch can be clearer when choosing between known values:
int day = 2;
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
default -> System.out.println("Another day");
}
This arrow-style syntax is available in modern Java versions. In older Java versions, use the traditional case and break form supported by that version.
Common mistakes#
- Using
=instead of==when comparing primitive values. Assignment and comparison are different operations. - Forgetting braces around multi-statement branches.
- Testing a broad condition before a more specific condition, making the latter unreachable.
- Comparing strings with
==when you intend to compare their contents; use.equals()instead.
Practice#
Create an integer temperature. Print “Cold” below 15, “Comfortable” from 15 through 25, and “Hot” above 25. Test boundary values such as 15 and 25.