Conditional Statements: Branch Your Program Logic
Introduction
This chapter covers conditional statements in Java—ways to run different code based on conditions. You will use if / else, the ternary operator, and switch. These build on Operators and prepare you for Loops and practice games later.
Prerequisites
What Is a Conditional
A conditional chooses which block of code runs.
Metaphor: a railway switch—depending on the signal (condition), the train takes track A or track B.
int age = 20;
if (age >= 18) {
System.out.println("Access granted");
} else {
System.out.println("Access denied");
}1) if and else
int score = 85;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 80) {
System.out.println("Good");
} else if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Need improvement");
}Notes:
- Conditions must be boolean expressions
- Braces
{ }are required for multi-line blocks (single-line without braces is legal but discouraged for beginners) - Java uses
else if(two words), notelif
Warning
Use == for primitive comparison, .equals() for String content. Do not use = in conditions—that is assignment.
2) Ternary Operator (? :)
Compact form for simple either/or values:
int age = 17;
String label = (age >= 18) ? "Adult" : "Minor";
System.out.println(label);Structure: (condition) ? valueIfTrue : valueIfFalse
Use when both branches are simple expressions. For long logic, prefer if / else for readability.
3) switch Statements
switch selects among multiple cases—often cleaner than long else if chains when comparing one value.
Classic switch (with break)
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
break;
}break stops fall-through to the next case. Without break, execution “falls through” subsequent cases—sometimes intentional, usually a bug for beginners.
switch on String (Java 7+)
String command = "start";
switch (command) {
case "start":
System.out.println("Starting...");
break;
case "stop":
System.out.println("Stopping...");
break;
default:
System.out.println("Unknown command");
break;
}Modern switch expression (Java 14+, idiomatic on 21)
Arrow syntax avoids many break mistakes and can return a value:
String dayLabel = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Other day";
};
System.out.println(dayLabel);Multiple labels per branch:
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};4) Combining Conditions
Use logical operators from Operators:
int age = 20;
boolean hasTicket = true;
if (age >= 18 && hasTicket) {
System.out.println("Enter");
} else if (age < 18) {
System.out.println("Too young");
} else {
System.out.println("Need a ticket");
}5) Real Mini Example: Login Gate
import java.util.Scanner;
public class LoginGate {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Username: ");
String username = scanner.nextLine().strip();
System.out.print("Password: ");
String password = scanner.nextLine();
if (username.isEmpty() || password.isEmpty()) {
System.out.println("Username and password are required.");
} else if ("admin".equals(username) && "java123".equals(password)) {
System.out.println("Welcome, admin!");
} else {
System.out.println("Invalid credentials.");
}
}
}
}Common Beginner Mistakes
Mistake 1: Using = Instead of ==
// if (score = 90) // compile error in Java — good safety net
if (score == 90) { }Mistake 2: Comparing Strings with ==
if ("yes".equals(userInput)) { } // correct for contentMistake 3: Missing break in Classic switch
Causes unintended fall-through. Use arrow switch or add break deliberately.
Mistake 4: Ternary Overuse
Nested ternaries become unreadable. Prefer if / else for complex logic.
Mini Practice
Write a program that reads an integer hour (0–23) and prints:
Good morningfor 5–11Good afternoonfor 12–17Good eveningfor 18–21Good nightotherwise
Try both if / else and switch versions.
What’s Next
Repeat actions with Loop Statements, then store sequences in Arrays.
FAQ
When should I use switch instead of if / else?
When one expression maps to many discrete values (int, enum, String). For ranged checks (score ranges), if / else is often clearer.
Does switch work with double?
No. switch supports byte, short, char, int, Byte, Short, Character, Integer, enum, and String (and related patterns in newer Java).
What is fall-through?
When a case runs without break, execution continues into the next case. Arrow syntax (->) avoids fall-through by default.
Can I nest if statements?
Yes. Keep nesting shallow for readability—early return (in methods) or combined conditions often help.
How does the ternary operator relate to if / else?
It is an expression that picks one of two values. if / else is a statement for broader side effects (println, loops, etc.).