
Programs need to make decisions. Should the user see an error message? Did they enter the correct password? Is the score high enough to qualify? Conditionals let your code choose different paths based on conditions.
The if Statement
The simplest conditional checks one condition and runs code if it’s true.
int age = 20;
if (age >= 18) {
System.out.println("You can vote");
}
The condition goes in parentheses. The code to run goes in curly braces. If the condition is false, Java skips the block entirely.
The condition must evaluate to a boolean. Java doesn’t treat numbers as true or false like some languages do.
int count = 5;
// This works in some languages but not Java
if (count) { // Error: incompatible types
}
// Java requires an explicit boolean
if (count > 0) { // Correct
System.out.println("Count is positive");
}
The else Clause
Add an else block to run code when the condition is false.
int age = 16;
if (age >= 18) {
System.out.println("You can vote");
} else {
System.out.println("You cannot vote yet");
}
Exactly one of these blocks runs. Never both, never neither.
The else if Chain
Test multiple conditions in sequence with else if.
int score = 85;
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");
}
Java checks conditions from top to bottom and runs the first block where the condition is true. Once a match is found, it skips all remaining else if and else blocks.
Order matters. If you put score >= 60 first, a score of 95 would get a D because 95 is greater than or equal to 60. Put the most restrictive conditions first.
Nested Conditionals
You can put if statements inside other if statements.
boolean hasTicket = true;
boolean hasID = true;
if (hasTicket) {
if (hasID) {
System.out.println("Welcome to the event");
} else {
System.out.println("ID required");
}
} else {
System.out.println("Ticket required");
}
Nesting works but can get hard to follow. Often you can flatten nested conditions with logical operators.
if (hasTicket && hasID) {
System.out.println("Welcome to the event");
} else if (hasTicket && !hasID) {
System.out.println("ID required");
} else {
System.out.println("Ticket required");
}
Both approaches work. Choose whichever reads more clearly for your situation.
Common Comparison Patterns
Some patterns appear constantly in conditionals.
Checking Ranges
int temperature = 72;
if (temperature < 60) {
System.out.println("Cold");
} else if (temperature < 80) {
System.out.println("Comfortable");
} else {
System.out.println("Hot");
}
Checking Equality
String status = "active";
if (status.equals("active")) {
System.out.println("Account is active");
} else if (status.equals("suspended")) {
System.out.println("Account is suspended");
} else {
System.out.println("Unknown status");
}
Remember: use .equals() for String comparison, not ==.
Checking for Null
String username = getUserInput();
if (username == null) {
System.out.println("No username provided");
} else if (username.isEmpty()) {
System.out.println("Username cannot be empty");
} else {
System.out.println("Hello, " + username);
}
Check for null before calling methods on an object. Calling .isEmpty() on null throws a NullPointerException.
Combining Conditions
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = true;
if (age >= 18 && hasLicense && hasInsurance) {
System.out.println("You can rent a car");
} else {
System.out.println("Requirements not met");
}
The switch Statement
When you’re comparing one value against many possible matches, switch can be cleaner than a chain of else if statements.
int dayNumber = 3;
switch (dayNumber) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
The break statement exits the switch. Without it, execution falls through to the next case.
Fall-Through Behavior
Sometimes fall-through is useful.
int month = 2;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("31 days");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println("30 days");
break;
case 2:
System.out.println("28 or 29 days");
break;
default:
System.out.println("Invalid month");
}
Multiple cases can share the same code block by stacking them.
Switch with Strings
Since Java 7, switch works with Strings.
String command = "start";
switch (command.toLowerCase()) {
case "start":
System.out.println("Starting...");
break;
case "stop":
System.out.println("Stopping...");
break;
case "restart":
System.out.println("Restarting...");
break;
default:
System.out.println("Unknown command");
}
Switch Expressions (Java 14+)
Modern Java offers a cleaner switch syntax that returns values and doesn’t need break statements.
int dayNumber = 3;
String dayName = switch (dayNumber) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day";
};
System.out.println(dayName); // Wednesday
The arrow syntax (->) replaces the colon and eliminates fall-through. Each case returns a value directly.
You can group cases:
int month = 4;
int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> 28;
default -> -1;
};
System.out.println(month + " has " + days + " days");
For multi-line case blocks, use yield to return the value:
String grade = "B";
String feedback = switch (grade) {
case "A" -> "Excellent work";
case "B" -> {
System.out.println("Calculating feedback...");
yield "Good job";
}
case "C" -> "Satisfactory";
default -> "Needs improvement";
};
The Ternary Operator
For simple if-else assignments, the ternary operator is compact.
int score = 75;
String result = (score >= 60) ? "Pass" : "Fail";
System.out.println(result); // Pass
The syntax: condition ? valueIfTrue : valueIfFalse
Use it for simple cases. Complex conditions belong in regular if-else blocks.
// Good use of ternary
int a = 10, b = 20;
int max = (a > b) ? a : b;
// Too complex for ternary - use if-else instead
String status = (age >= 18 && hasID && !isBanned) ? "allowed" : "denied";
Practical Example
Here’s a program that determines shipping costs based on order details:
public class ShippingCalculator {
public static void main(String[] args) {
double orderTotal = 75.00;
String destination = "domestic";
boolean isPremiumMember = true;
double shippingCost;
// Premium members get free shipping on orders over $50
if (isPremiumMember && orderTotal >= 50) {
shippingCost = 0;
} else {
// Calculate based on destination
switch (destination.toLowerCase()) {
case "domestic":
if (orderTotal >= 100) {
shippingCost = 0; // Free shipping over $100
} else if (orderTotal >= 50) {
shippingCost = 5.99;
} else {
shippingCost = 9.99;
}
break;
case "canada":
shippingCost = 14.99;
break;
case "international":
shippingCost = 24.99;
break;
default:
shippingCost = -1; // Invalid destination
}
}
if (shippingCost < 0) {
System.out.println("Invalid destination");
} else if (shippingCost == 0) {
System.out.println("Free shipping!");
System.out.println("Order total: $" + orderTotal);
} else {
System.out.println("Shipping: $" + shippingCost);
System.out.println("Order total: $" + (orderTotal + shippingCost));
}
}
}
Output:
Free shipping!
Order total: $75.0
Common Mistakes
Using = instead of == in conditions. Single equals assigns. Double equals compares. Java catches this in boolean contexts, but stay alert.
int x = 5;
if (x = 10) { // Error: incompatible types
}
if (x == 10) { // Correct
}
Comparing Strings with ==. Use .equals() for String content comparison.
String a = "hello";
if (a == "hello") { // Unreliable
}
if (a.equals("hello")) { // Correct
}
Forgetting break in switch. Without break, execution falls through to the next case. Sometimes intentional, often a bug.
Not handling null. Check for null before calling methods on objects that might be null.
String name = null;
if (name.equals("test")) { // NullPointerException!
}
if (name != null && name.equals("test")) { // Safe
}
Wrong condition order. In else-if chains, put specific conditions before general ones. Check for null before checking content.
What’s Next
Conditionals let your program choose one path. Loops let it repeat actions. The next tutorial covers for loops, while loops, and controlling loop execution with break and continue.
Related: Working with Strings in Java | Java Loops: for, while, do-while
Sources
- Oracle. “The if-then and if-then-else Statements.” The Java Tutorials. docs.oracle.com
- Oracle. “The switch Statement.” The Java Tutorials. docs.oracle.com


