If-Else Statements
Overview
If-Else statements are the primary mechanism for Control Flow in Java. They allow your program to make decisions and execute different blocks of code based on dynamic conditions (like user input or server responses).
Without conditional logic, a program would just execute in a straight, boring line from top to bottom. With if, else if, and else, you can branch your logic to handle infinite scenarios.
Java also provides a condensed version of the if-else statement known as the Ternary Operator. It is a one-line shorthand used specifically when you want to assign a value to a variable based on a simple boolean condition.
Syntax
The else if ladder is evaluated top-to-bottom. As soon as ONE condition is true, its block executes and the rest of the ladder is completely skipped. The Ternary operator is excellent for clean, inline assignments.
public class Main {
public static void main(String[] args) {
int score = 85;
// --- 1. Standard If-Else-If Ladder ---
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B"); // This executes!
} else {
System.out.println("Grade: F");
}
// --- 2. The Ternary Operator ---
// Syntax: variable = (condition) ? expressionTrue : expressionFalse;
int time = 20;
String greeting = (time < 18) ? "Good day." : "Good evening.";
System.out.println(greeting); // Prints "Good evening."
}
}Common Pitfalls
- Placing a semicolon directly after the if condition:
if (x > 5); { ... }. The compiler thinks theifstatement is finished at the semicolon, and the block of code inside{}will execute unconditionally every single time! - Confusing
=(assignment) with==(comparison).if (x = 5)will throw a compilation error in Java becausex=5returns an integer, and Javaifstatements strictly require aboolean. - Overusing the Ternary operator. Nesting ternaries inside other ternaries makes code utterly unreadable. If the logic requires more than one simple condition, always use standard
if-elseblocks.
Interview Questions
if statement exist without an else block?Yes. An if statement can exist entirely on its own. The else and else if blocks are entirely optional extensions.
{} around an if block?Java will only execute the very next single line of code under the if statement conditionally. Any lines after that will execute normally. This is considered a severe anti-pattern (known as 'Apple's goto fail bug') because it leads to highly deceptive indentation errors. Always use curly braces.
Real-World Example
Payment gateways use complex if-else logic to route transactions based on the user's selected payment method, ensuring the correct external API is called.
public void processPayment(String method) {
if (method.equals("CREDIT_CARD")) {
stripeApi.charge();
} else if (method.equals("PAYPAL")) {
paypalApi.redirect();
} else {
throw new RuntimeException("Invalid Payment Method");
}
}Check Your Knowledge
Test your understanding of If-Else Statements with these quick questions.