Conditional Statements
if-else, switch-case, and decision making
1. Overview & Types
Conditional statements control program flow by executing different code blocks based on conditions.
If Statement
Execute code when condition is true
if (condition) { }
Switch Statement
Multiple conditions with single variable
switch (variable) { }
Ternary Operator
Shorthand for simple if-else
condition ? value1 : value2
Decision Flow
Condition (Evaluate Expression) → Decision (True or False?) → Action (Execute Code Block)
2. If Statements
Simple If
int age = 18;
if (age >= 18) {
System.out.println("You can vote!");
}
If-Else
int score = 85;
if (score >= 90) {
System.out.println("Grade A");
} else {
System.out.println("Grade B or below");
}
If-Else If-Else
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 {
System.out.println("Grade F");
}
Comparison Conditions
age > 18
score == 100
name != null
price <= 50.0
Logical Conditions
age >= 18 && hasLicense
day == “Saturday” || day == “Sunday”
!isExpired
(x > 0) && (x < 100)
Nested If Statements
boolean isRaining = true;
int temperature = 25;
if (isRaining) {
if (temperature 15) {
System.out.println("Wear a raincoat and jacket");
} else {
System.out.println("Just carry an umbrella");
}
} else {
if (temperature > 30) {
System.out.println("Wear light clothes");
} else {
System.out.println("Normal clothes are fine");
}
}
3. Switch Statements
Switch statements provide a clean way to handle multiple conditions on a single variable.
Traditional Switch
int dayOfWeek = 3;
switch (dayOfWeek) {
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");
}
Switch Expression (Java 14+)
String dayName = switch (dayOfWeek) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> "Weekend";
};
Multiple Cases & String Switch
switch (grade) {
case 'A':
case 'B':
System.out.println("Good work!");
break;
case 'C':
System.out.println("Average");
break;
default:
System.out.println("Needs improvement");
}
Important Notes
- Break statements: Prevent fall-through to next case
- Default case: Always include for unmatched values
- Supported types: byte, short, int, char, String, enum
4. Ternary Operator
The ternary operator provides a concise way to write simple if-else statements in one line.
Syntax
condition ? valueIfTrue : valueIfFalse
Before and After Comparison
// Before (If-Else)
int age = 20;
String status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
// After (Ternary) - Much cleaner!
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
Common Use Cases
- Variable Assignment:
int max = (a > b) ? a : b; - Method Parameters:
println(score > 90 ? "Pass" : "Fail"); - Return Values:
return (count == 0) ? "Empty" : "Has items"; - Null Safety:
String name = (user != null) ? user.getName() : "Guest";
Nested Ternary (Use Sparingly)
// Grade calculation using nested ternary
int score = 85;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "F";
// Better approach for complex conditions - use if-else
String grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else grade = "F";
5. Practical Examples
User Authentication
String username = "admin";
String password = "123456";
if (username.equals("admin") && password.equals("123456")) {
System.out.println("Login successful");
} else {
System.out.println("Invalid credentials");
}
Calculator App
double a = 10, b = 5;
String operator = "+";
double result = switch (operator) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
case "/" -> (b != 0) ? a / b : 0;
default -> 0;
};
Payment Processing
double amount = 150.0;
double balance = 200.0;
boolean isVip = true;
if (amount double discount = isVip ? 0.1 : 0.05;
double finalAmount = amount * (1 - discount);
System.out.println("Payment approved: $" + finalAmount);
} else {
System.out.println("Insufficient funds");
}
6. Best Practices
Good Practices
- Use meaningful boolean variable names
- Keep conditions simple and readable
- Always include default case in switch
- Use ternary for simple assignments
- Avoid deep nesting (max 2-3 levels)
- Use parentheses for complex conditions
Avoid These
- Complex nested ternary operators
- Missing break statements in switch
- Magic numbers in conditions
- Deep nesting (arrow anti-pattern)
- Comparing booleans with == true
- Long switch statements
Clean Code Example
// ❌ Hard to Read
if (user.getAge() >= 18 && user.getAge() 65 && user.isActive() == true && user.getBalance() > 1000) {
processPayment();
}
// ✅ Easy to Read
boolean isEligibleAge = user.getAge() >= 18 && user.getAge() 65;
boolean hasValidAccount = user.isActive() && user.getBalance() > 1000;
if (isEligibleAge && hasValidAccount) {
processPayment();
}
Performance Tips
- Short-Circuit Evaluation: Place simpler conditions first in logical operators
- Switch vs If-Else: Use switch for 3+ discrete values, if-else for ranges
- Early Return: Return early to reduce nesting levels
What’s Next?
- Learn Loops (for, while, do-while)
- Master Arrays and Collections
- Explore Object-Oriented Programming
- Practice Exception Handling