Decision-making with conditions
Conditional logic lets a program choose between different paths (branches) based on whether a condition is true or false. In Java, conditions are boolean expressions, meaning they evaluate to true or false. The most common tools are if, else if, else, and switch.
Boolean expressions (what can go inside an if)
An if statement requires a boolean expression in parentheses. You typically build boolean expressions using comparison operators like >, >=, <, <=, ==, != and logical operators like && (and), || (or), and ! (not).
int score = 82; boolean passed = score >= 50; boolean excellent = score >= 90; boolean inRange = score >= 0 && score <= 100; boolean notExcellent = !excellent;Common patterns you will use often:
- Range checks:
age >= 13 && age <= 19 - One of many:
day == 6 || day == 7 - Negation:
!isLoggedIn
Basic if / else
if runs a block only when the condition is true. else runs when the condition is false. Exactly one branch runs.
int temperature = 28; if (temperature >= 30) { System.out.println("It's hot"); } else { System.out.println("Not too hot"); }If the block contains only one statement, braces are optional, but beginners should keep braces to avoid mistakes.
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
boolean hasTicket = true; if (hasTicket) { System.out.println("Enter the event"); } else { System.out.println("Buy a ticket first"); }Step-by-step: tracing which branch runs
When you read an if/else, trace it in this order:
- Evaluate the condition in the
if. - If it is
true, run theifblock and skip theelse. - If it is
false, skip theifblock and run theelseblock.
int x = 10; if (x > 10) { System.out.println("A"); } else { System.out.println("B"); }Trace: x > 10 is false, so it prints B.
else-if chains (multiple choices)
Use an else if chain when there are multiple mutually exclusive choices. Java checks conditions from top to bottom and runs the first matching branch. If none match, the final else (if present) runs.
int score = 82; 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"); }Real-world scenario 1: grading thresholds
Grading is a classic example because the conditions are ordered thresholds. The order matters: you must check the highest threshold first, otherwise a score like 95 would match score >= 80 too early.
Step-by-step for score = 82:
score >= 90is false, continue.score >= 80is true, printGrade: B, stop checking.
Real-world scenario 2: ticket pricing by age
Ticket pricing often uses age brackets. Here is an example with clear, non-overlapping ranges.
int age = 15; int price; if (age < 0) { price = -1; // invalid } else if (age <= 5) { price = 0; // free } else if (age <= 12) { price = 8; } else if (age <= 17) { price = 10; } else if (age <= 64) { price = 15; } else { price = 9; // senior } System.out.println("Price: " + price);Notes for correctness:
- Use
<=to include the boundary ages (like 12, 17, 64). - Start with invalid inputs if you want to guard against them.
- Make ranges cover all valid ages so you do not accidentally miss a case.
Real-world scenario 3: login-like checks with boolean flags
Many programs decide access based on boolean flags such as whether the user is logged in, whether the password is correct, or whether the account is locked. You can model this with booleans and an if/else if chain.
boolean usernameExists = true; boolean passwordCorrect = false; boolean accountLocked = false; if (!usernameExists) { System.out.println("Unknown user"); } else if (accountLocked) { System.out.println("Account locked"); } else if (!passwordCorrect) { System.out.println("Wrong password"); } else { System.out.println("Login successful"); }Why this order?
- Checking
!usernameExistsfirst avoids revealing extra details for users that do not exist. - Checking
accountLockedearly prevents login even if the password is correct. - Only when all required conditions are satisfied do you allow access.
switch for discrete options (menu selection)
Use switch when you select a branch based on a single value that represents discrete options (for example, a menu choice). A switch can be clearer than a long chain of else if comparisons against the same variable.
switch with int (menu selection)
int choice = 2; switch (choice) { case 1: System.out.println("Create new file"); break; case 2: System.out.println("Open file"); break; case 3: System.out.println("Save file"); break; case 4: System.out.println("Exit"); break; default: System.out.println("Invalid choice"); }Key rules:
switchevaluates the expression once.caselabels are the possible matching values.breakstops execution of the switch. Without it, execution continues into the next case (called fall-through).defaultruns when no case matches (similar to anelse).
Intentional fall-through (advanced but useful)
Sometimes you want multiple cases to share the same behavior. You can group them by letting one case fall through into another.
int day = 6; switch (day) { case 6: case 7: System.out.println("Weekend"); break; default: System.out.println("Weekday"); }switch with String
switch also works with String, which is useful for text-based commands.
String command = "start"; switch (command) { case "start": System.out.println("Starting..."); break; case "stop": System.out.println("Stopping..."); break; case "status": System.out.println("Showing status..."); break; default: System.out.println("Unknown command"); }Structured practice
Practice 1: write boolean conditions
Create boolean variables for each requirement. Assume the variables exist as shown.
- Write a condition that is true when
ageis between 13 and 19 inclusive. - Write a condition that is true when
scoreis NOT in the range 0 to 100. - Write a condition that is true when
isAdminis true ORisModeratoris true. - Write a condition that is true when the user is logged in (
isLoggedIn) AND email is verified (emailVerified).
// Your turn: replace ??? with boolean expressions int age = 0; int score = 0; boolean isAdmin = false; boolean isModerator = false; boolean isLoggedIn = false; boolean emailVerified = false; boolean teen = ???; boolean invalidScore = ???; boolean staff = ???; boolean canAccess = ???;Practice 2: trace which branch runs
For each set of values, write down which message prints. Do it by evaluating conditions from top to bottom.
int score = 0; if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else if (score >= 70) { System.out.println("C"); } else { System.out.println("F"); }- Case 1:
score = 95 - Case 2:
score = 80 - Case 3:
score = 79 - Case 4:
score = 10
Practice 3: refactor an if/else chain into a switch
The following code compares the same variable (choice) against discrete values. This is a good candidate for a switch. Rewrite it using switch with the same behavior.
int choice = 3; if (choice == 1) { System.out.println("Add item"); } else if (choice == 2) { System.out.println("Remove item"); } else if (choice == 3) { System.out.println("Checkout"); } else if (choice == 4) { System.out.println("Help"); } else { System.out.println("Invalid"); }Checklist for your refactor:
- Use
switch (choice). - Create
case 1throughcase 4. - Include a
defaultcase. - Add
breakafter each case to prevent fall-through.
Practice 4: choose between if/else and switch
Decide which structure fits best and explain why:
- Pricing by age bracket (ranges like 0–5, 6–12, 13–17, ...)
- Menu selection by numeric option (1, 2, 3, 4)
- Checking access rules that combine multiple flags (logged in, verified, locked)