By the end of this module, you will be able to:
if / else if / else statements using Java's comparison and logical operatorsswitch statements in both classic and modern enhanced syntaxfor, enhanced for, while, and do-while loopsbreak and continue to alter loop executionif / else if / elseThe syntax is nearly identical to JavaScript. The condition inside the parentheses must be a boolean expression — Java has no truthy/falsy values.
int temperature = 22;
if (temperature > 30) {
System.out.println("It's hot outside.");
} else if (temperature >= 15) {
System.out.println("Nice weather.");
} else {
System.out.println("It's cold outside.");
}
// Nice weather.
⚠️ Unlike JavaScript,
if (score)orif (name)will not compile. You must write an explicit boolean expression:if (score > 0)orif (name != null).
These evaluate to true or false and form the conditions in your if statements and loops.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
true |
!= |
Not equal to | 5 != 3 |
true |
< |
Less than | 3 < 7 |
true |
> |
Greater than | 7 > 3 |
true |
<= |
Less than or equal | 5 <= 5 |
true |
>= |
Greater than or equal | 4 >= 6 |
false |
== on Strings compares memory references, not content. Always use .equals():
String input = "yes";
if (input == "yes") { ... } // ❌ may not work as expected
if (input.equals("yes")) { ... } // ✅ always correct
🔍 This is the same concept as
===in JavaScript checking reference equality for objects — in Java,==does the same for all reference types.
Use logical operators to combine multiple boolean expressions.
| Operator | Meaning | Example | Result |
|---|---|---|---|
&& |
AND — both must be true | age > 18 && hasID |
true only if both are true |
| ` | ` | OR — at least one must be true | |
! |
NOT — inverts the boolean | !isLoggedIn |
true if isLoggedIn is false |
int age = 20;
boolean hasTicket = true;
if (age >= 18 && hasTicket) {
System.out.println("Entry granted.");
}
boolean isWeekend = false;
boolean isHoliday = true;
if (isWeekend || isHoliday) {
System.out.println("Office is closed.");
}
boolean isLoggedIn = false;
if (!isLoggedIn) {
System.out.println("Please log in first.");
}
Java stops evaluating as soon as the result is determined:
&& — if the left side is false, the right side is never evaluated|| — if the left side is true, the right side is never evaluatedString name = null;
// Safe — if name is null, the right side is never reached
if (name != null && name.equals("Alice")) {
System.out.println("Hello, Alice!");
}
💡 Short-circuit evaluation is a useful defensive pattern — always put the cheaper or null-safety check on the left side of
&&.
switch StatementUse switch when you have one variable with many possible discrete values. It's cleaner than a long chain of else if.
switchString day = "Wednesday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.println("Weekday");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend");
break;
default:
System.out.println("Unknown day");
}
⚠️ The
breakstatement is mandatory in classicswitch. Without it, execution falls through into the next case and keeps running until it hits abreakor the end of theswitch. This is the same behaviour as JavaScript.
The modern syntax removes fall-through entirely and can return a value directly. No break needed.
String day = "Wednesday";
String type = switch (day) {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday";
case "Saturday", "Sunday" -> "Weekend";
default -> "Unknown day";
};
System.out.println(type); // Weekday
💡 Prefer the enhanced syntax for new code — it's less error-prone and more expressive. The classic syntax still appears frequently in existing codebases, so it's important to recognise both.
for LoopThe traditional for loop gives you full control over the counter variable. The structure has three parts: initialise, condition, update.
// init condition update
for (int i = 0; i < 5; i++) {
System.out.println("Step: " + i);
}
// Step: 0
// Step: 1
// Step: 2
// Step: 3
// Step: 4
The three parts are flexible — you can count down, skip values, or use any step size:
// Count down
for (int i = 10; i >= 0; i--) {
System.out.println(i);
}
// Step by 2
for (int i = 0; i <= 10; i += 2) {
System.out.println(i); // 0, 2, 4, 6, 8, 10
}
Use the traditional for loop when:
for Loop (for-each)A cleaner, safer way to iterate over arrays and collections when you only need the values, not the index.
String[] languages = {"Java", "Python", "JavaScript"};
for (String language : languages) {
System.out.println(language);
}
// Java
// Python
// JavaScript
🔍 This is Java's equivalent of
for...ofin JavaScript. It's the preferred loop when you don't need the index — it's shorter, avoids off-by-one errors, and reads naturally.
You cannot use the enhanced for loop when:
while and do-while Loopswhile — check first, then runUse when the loop should only run if the condition is initially true. The number of iterations is not known upfront.
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
A common real-world use case — keep asking until valid input is received:
Scanner scanner = new Scanner(System.in);
int age = -1;
while (age < 0 || age > 120) {
System.out.print("Enter a valid age: ");
age = scanner.nextInt();
}
System.out.println("Age accepted: " + age);
do-while — run first, then checkThe body always executes at least once, regardless of the condition. Useful when you need to show a menu or prompt before knowing whether to continue.
Scanner scanner = new Scanner(System.in);
String choice;
do {
System.out.println("1. Start");
System.out.println("2. Help");
System.out.println("3. Quit");
System.out.print("Choose an option: ");
choice = scanner.nextLine();
} while (!choice.equals("3"));
System.out.println("Goodbye!");
💡 Rule of thumb: use
whilewhen the loop might not need to run at all. Usedo-whilewhen it must run at least once — like displaying a menu before reading a choice.
break and continueBoth alter the normal flow of a loop.
break — exit the loop immediately