Java if-else Statement â Syntax, Types, Examples & Best Practices
Everything you need to know about Java if-else â simple if, if-else, if-else-if ladder, nested conditions, ternary operator, pattern matching (Java 16+), anti-patterns, and real-world production code examples.
Last Updated
March 2026
Read Time
22 min
Level
Beginner
Chapter
12 of 35
What is the if-else Statement in Java?
The if-else statement in Java is the most fundamental conditional control flow construct. It allows a program to make decisions â executing one block of code when a condition is true, and optionally executing a different block when it is false. Without if-else, every program would execute statements in a fixed, top-to-bottom sequence, with no ability to branch based on data or user input.
In real-world applications, conditional logic is everywhere: if the user is logged in, show the dashboard; else redirect to login. If the account balance is sufficient, process the payment; else show an error. If the temperature exceeds 100°C, trigger the alarm; else continue monitoring. Every decision your program makes flows through some form of if-else logic.
Java's if-else is strictly boolean-based â the condition must evaluate to either true or false. Unlike C/C++, Java does not allow integer expressions like if(1) or if(count) â this produces a compile-time error. This strictness makes Java code more readable and prevents a common class of bugs.
Simple if Statement â One-Way Selection
The simple if statement is a one-way selection: the body executes only when the condition is true. When the condition is false, the block is skipped entirely and execution moves to the next statement after the if block. No else clause is involved.
if (condition) { // statement(s) executed only when condition == true } // execution always continues here
1. The condition MUST be a boolean expression â int/char/other types cause compile errors. 2. Curly braces {} are optional for single-statement bodies, but always recommended. 3. The condition is evaluated at runtime â any expression returning boolean is valid.
Evaluate condition â if TRUE: execute block, then continue â if FALSE: skip block, continue. Either way, program continues after the if statement.
public class SimpleIf {
public static void main(String[] args) {
int temperature = 38;
// â
Simple if â executes only when condition is true
if (temperature > 37) {
System.out.println("Fever detected! Please consult a doctor.");
}
// Execution always reaches here regardless of condition
System.out.println("Temperature check complete.");
// â
Another example â checking login status
boolean isLoggedIn = true;
if (isLoggedIn) {
System.out.println("Welcome back, User!");
loadUserPreferences();
}
// â
Single statement â braces optional (but NOT recommended)
int age = 20;
if (age >= 18)
System.out.println("Eligible to vote."); // Risky â avoid
// â Compile Error â condition is int, not boolean
// if (temperature) { } // ERROR: incompatible types: int cannot be converted to boolean
}
static void loadUserPreferences() {
System.out.println("User preferences loaded.");
}
}if-else Statement â Two-Way Selection
The if-else statement provides a two-way selection: when the condition is true, the if block executes; when it is false, the else block executes. Exactly one of the two blocks always runs â never both, never neither. This guarantees complete coverage of all cases.
public class IfElse {
public static void main(String[] args) {
// Example 1: Voting eligibility
int age = 16;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote yet.");
System.out.println("Come back in " + (18 - age) + " year(s).");
}
// Output: You are not eligible to vote yet.
// Come back in 2 year(s).
// Example 2: Bank transaction
double accountBalance = 5000.00;
double withdrawalAmount = 7500.00;
if (accountBalance >= withdrawalAmount) {
accountBalance -= withdrawalAmount;
System.out.println("Withdrawal successful. New balance: " + accountBalance);
} else {
System.out.println("Insufficient funds.");
System.out.println("Available balance: " + accountBalance);
}
// Output: Insufficient funds.
// Available balance: 5000.0
// Example 3: Even or Odd
int number = 47;
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
// Output: 47 is Odd.
}
}if-else-if Ladder â Multi-Way Selection
The if-else-if ladder (also called an else-if chain) tests multiple conditions sequentially from top to bottom. The first condition that evaluates to true has its block executed â all subsequent conditions are then skipped. The optional final else acts as a default case, executing when no condition is true.
public class IfElseIfLadder {
public static void main(String[] args) {
// Example 1: Grade Classification
int marks = 72;
if (marks >= 90) {
System.out.println("Grade: A+ (Outstanding)");
} else if (marks >= 80) {
System.out.println("Grade: A (Excellent)");
} else if (marks >= 70) {
System.out.println("Grade: B (Good)"); // â This executes
} else if (marks >= 60) {
System.out.println("Grade: C (Average)");
} else if (marks >= 40) {
System.out.println("Grade: D (Pass)");
} else {
System.out.println("Grade: F (Fail)");
}
// Output: Grade: B (Good)
// Example 2: Income Tax Slabs (India - simplified)
double annualIncome = 850000;
double taxAmount;
if (annualIncome <= 300000) {
taxAmount = 0;
} else if (annualIncome <= 600000) {
taxAmount = (annualIncome - 300000) * 0.05;
} else if (annualIncome <= 900000) {
taxAmount = 15000 + (annualIncome - 600000) * 0.10;
} else if (annualIncome <= 1200000) {
taxAmount = 45000 + (annualIncome - 900000) * 0.15;
} else if (annualIncome <= 1500000) {
taxAmount = 90000 + (annualIncome - 1200000) * 0.20;
} else {
taxAmount = 150000 + (annualIncome - 1500000) * 0.30;
}
System.out.println("Tax payable: âš" + taxAmount);
// Output: Tax payable: âš40000.0
}
}Nested if-else â Hierarchical Decision Making
A nested if-else is an if-else statement placed inside the body of another if or else block. This allows decisions that depend on prior decisions â creating a decision tree structure. While powerful, deep nesting quickly becomes difficult to read and maintain â the so-called "arrow code" or "pyramid of doom" anti-pattern.
public class NestedIfElse {
public static void main(String[] args) {
// Example 1: Loan Eligibility
int age = 28;
double monthlyIncome = 55000;
double existingDebt = 10000;
boolean hasCriminalRecord = false;
if (age >= 21 && age <= 65) {
if (monthlyIncome >= 25000) {
if (!hasCriminalRecord) {
if (existingDebt < monthlyIncome * 0.5) {
System.out.println("Loan APPROVED â
");
} else {
System.out.println("Loan REJECTED â High existing debt");
}
} else {
System.out.println("Loan REJECTED â Criminal record found");
}
} else {
System.out.println("Loan REJECTED â Insufficient income");
}
} else {
System.out.println("Loan REJECTED â Age not in eligible range");
}
// Output: Loan APPROVED â
// â
BETTER: Same logic refactored with Guard Clauses (flat structure)
System.out.println("--- Refactored with Guard Clauses ---");
checkLoanEligibility(age, monthlyIncome, existingDebt, hasCriminalRecord);
}
// â
Guard clause pattern â early return flattens nesting
static void checkLoanEligibility(int age, double income,
double debt, boolean hasCriminal) {
if (age < 21 || age > 65) {
System.out.println("REJECTED â Age not in eligible range");
return;
}
if (income < 25000) {
System.out.println("REJECTED â Insufficient income");
return;
}
if (hasCriminal) {
System.out.println("REJECTED â Criminal record found");
return;
}
if (debt >= income * 0.5) {
System.out.println("REJECTED â High existing debt");
return;
}
System.out.println("Loan APPROVED â
");
}
}Ternary Operator (?:) â Inline if-else
The ternary operator (?:) is Java's only three-operand operator. It is a compact, inline replacement for simple if-else statements that assign a value. Syntax: variable = (condition) ? valueIfTrue : valueIfFalse;. The name 'ternary' comes from Latin ternarius meaning 'consisting of three' â it takes three operands: a condition, a true-value, and a false-value.
public class TernaryOperator {
public static void main(String[] args) {
// Basic if-else vs ternary comparison
int age = 20;
// â Verbose: 5 lines for a simple assignment
String status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
// â
Ternary: 1 clean line
String statusTernary = (age >= 18) ? "Adult" : "Minor";
System.out.println(statusTernary); // Output: Adult
// â
Ternary in print statement
int number = -7;
System.out.println(number + " is " + (number >= 0 ? "positive" : "negative"));
// Output: -7 is negative
// â
Ternary for null-safe default values
String username = null;
String displayName = (username != null) ? username : "Guest";
System.out.println("Hello, " + displayName); // Output: Hello, Guest
// â
Ternary with method calls
double price = 1500.0;
double discount = (price > 1000) ? price * 0.10 : price * 0.05;
System.out.println("Discount: âš" + discount); // Output: Discount: âš150.0
// â BAD: Nested ternary â avoid at all costs
int marks = 75;
String grade = (marks >= 90) ? "A" : (marks >= 70) ? "B" : (marks >= 50) ? "C" : "F";
// This compiles but is extremely hard to read â use if-else-if ladder instead
// â
GOOD: Use ternary ONLY for simple, flat conditions
int temperature = 35;
String weather = (temperature > 30) ? "Hot" : "Pleasant";
System.out.println("Weather: " + weather); // Output: Weather: Hot
}
}if-else vs switch â When to Use Which
Both if-else and switch are conditional control flow structures, but they serve different purposes. Choosing the right one makes your code more readable and in some cases more performant. Java 14+ switch expressions and Java 21 pattern matching switch have significantly expanded switch's capabilities.
// Scenario: Display day type based on day number
// â if-else â verbose for exact-match comparison
int day = 3;
String dayType;
if (day == 1 || day == 7) {
dayType = "Weekend";
} else if (day == 2 || day == 3 || day == 4 || day == 5 || day == 6) {
dayType = "Weekday";
} else {
dayType = "Invalid day";
}
// â
switch expression (Java 14+) â clean and expressive
String dayTypeSwitch = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Invalid day";
};
// Use if-else for range checks â switch can't do this
double bmi = 24.5;
String bmiCategory;
if (bmi < 18.5) {
bmiCategory = "Underweight";
} else if (bmi < 25.0) {
bmiCategory = "Normal weight"; // â matches
} else if (bmi < 30.0) {
bmiCategory = "Overweight";
} else {
bmiCategory = "Obese";
}
System.out.println("BMI Category: " + bmiCategory);Boolean Conditions in Depth â Writing Effective Conditions
The power of if-else depends entirely on the quality of its boolean condition expression. Java supports rich condition building using relational operators, logical operators, short-circuit evaluation, and method calls. Understanding these deeply prevents bugs and enables concise, correct conditions.
== (equal), != (not equal), > (greater), < (less), >= (greater or equal), <= (less or equal). WARNING: Use == for primitive types only. For objects (String, Integer, etc.), == checks reference equality (same memory address), not value equality. Always use .equals() for object content comparison: str.equals("hello") not str == "hello".
&& (AND): true only if BOTH sides are true. Short-circuits â right side NOT evaluated if left is false. || (OR): true if EITHER side is true. Short-circuits â right side NOT evaluated if left is true. Use short-circuit evaluation strategically: put cheaper/more likely conditions on the LEFT.
! (NOT): inverts a boolean. !true = false, !false = true. Prefer positive conditions over negative when possible: 'if (isActive)' is clearer than 'if (!isInactive)'. Double negation (!!isActive) is always code smell â simplify to (isActive). De Morgan's laws: !(A && B) = !A || !B, and !(A || B) = !A && !B.
Java's && and || use short-circuit evaluation. In 'if (obj != null && obj.isActive())', if obj is null, the second condition is NEVER evaluated (no NullPointerException). In 'if (list == null || list.isEmpty())', if list is null, isEmpty() is never called. Always put null checks and cheap checks FIRST in compound conditions.
Tests whether an object is an instance of a class: if (shape instanceof Circle). Java 16+ adds Pattern Matching: if (shape instanceof Circle c) â this both tests AND casts in one expression, eliminating explicit casting. Java 21 extends this to switch statements for sealed hierarchies.
Any method returning boolean can be a condition: if (user.isActive()), if (list.isEmpty()), if (str.contains("@")), if (file.exists()). This enables highly readable, self-documenting conditions. Prefer boolean-returning methods over manual flag variables: 'if (account.hasInsufficientFunds())' vs 'if (balance < amount)'.
import java.util.List;
public class ConditionExpressions {
public static void main(String[] args) {
// â
== for primitives, .equals() for objects
int a = 5, b = 5;
if (a == b) System.out.println("Primitive == works correctly");
String s1 = new String("hello");
String s2 = new String("hello");
if (s1.equals(s2)) System.out.println("String equals() â content match â
");
if (s1 == s2) System.out.println("This won't print â different objects â");
// â
Short-circuit: null-safe chaining
String username = null;
if (username != null && username.length() > 3) {
System.out.println("Username is valid");
} else {
System.out.println("Username is null or too short"); // â prints
}
// â
Compound conditions
int age = 25;
double income = 60000;
boolean hasGoodCreditScore = true;
if (age >= 21 && income >= 30000 && hasGoodCreditScore) {
System.out.println("Pre-approved for credit card");
}
// â
instanceof with Pattern Matching (Java 16+)
Object obj = "Hello, Java!";
if (obj instanceof String str) { // No explicit cast needed
System.out.println("String length: " + str.length()); // str is already String
}
// â
Boolean method conditions â most readable
List<String> errors = List.of();
if (errors.isEmpty()) {
System.out.println("No errors â proceeding");
}
}
}Common Mistakes & Pitfalls â Bugs That Fool Everyone
These mistakes are consistently found in Java beginner code, often pass code review unnoticed, and cause subtle runtime bugs. Study each one carefully â recognizing these patterns in your own code is a key skill.
// â MISTAKE 1: Assignment instead of comparison (= instead of ==)
// In Java this is a COMPILE ERROR (unlike C/C++ where it's a silent bug)
// int x = 5;
// if (x = 10) { } // ERROR: incompatible types: int cannot be converted to boolean
// â MISTAKE 2: String comparison with == (reference, not value)
String input = new String("yes");
if (input == "yes") { // â FALSE â different objects in memory
System.out.println("User confirmed"); // Never prints!
}
if (input.equals("yes")) { // â
TRUE â compares content
System.out.println("User confirmed"); // Prints correctly
}
// â MISTAKE 3: Missing braces causing logic error
boolean isAdmin = false;
boolean isLoggedIn = true;
if (isAdmin) // Only this line is conditional
System.out.println("Admin panel"); // Only executes when isAdmin=true
System.out.println("Logout button"); // â ALWAYS executes â not inside if!
// â MISTAKE 4: Checking boolean with == true (redundant)
boolean isActive = true;
if (isActive == true) { } // â Redundant â boolean IS the condition
if (isActive) { } // â
Direct and clean
if (isActive == false) { } // â Redundant
if (!isActive) { } // â
Use NOT operator
// â MISTAKE 5: Unreachable else due to wrong condition order
int score = 95;
if (score >= 40) {
System.out.println("Pass"); // Always matches first!
} else if (score >= 90) {
System.out.println("Distinction"); // â NEVER reached â 95>=40 already matched
}
// â
Fix: More specific condition first
if (score >= 90) {
System.out.println("Distinction"); // â
Now correctly matches 95
} else if (score >= 40) {
System.out.println("Pass");
}
// â MISTAKE 6: NullPointerException from reversed equals call
String status = null;
// if (status.equals("ACTIVE")) { } // â NPE â status is null!
if ("ACTIVE".equals(status)) { } // â
Literal first â null-safe
if (status != null && status.equals("ACTIVE")) { } // â
Also correctPattern Matching with instanceof â Java 16+ Feature
Java 16 introduced Pattern Matching for instanceof (JEP 394) â a major quality-of-life improvement that eliminates the verbose cast-after-check pattern. Instead of testing type with instanceof and then separately casting, you can do both in a single expression. The binding variable is only in scope where the pattern is guaranteed to match.
// Before Java 16 â verbose test-and-cast pattern
Object shape = new Circle(5.0);
// â Old way: 3 steps â test, cast, use
if (shape instanceof Circle) {
Circle c = (Circle) shape; // Redundant cast
System.out.println("Area: " + c.calculateArea());
}
// â
Java 16+ Pattern Matching: test + bind in one step
if (shape instanceof Circle c) {
// 'c' is automatically a Circle here â no cast needed
System.out.println("Area: " + c.calculateArea());
}
// â
With condition on the bound variable (Java 16+)
if (shape instanceof Circle c && c.getRadius() > 3.0) {
System.out.println("Large circle with area: " + c.calculateArea());
}
// â
Polymorphic method using pattern matching
static double calculateArea(Object shape) {
if (shape instanceof Circle c) {
return Math.PI * c.getRadius() * c.getRadius();
} else if (shape instanceof Rectangle r) {
return r.getWidth() * r.getHeight();
} else if (shape instanceof Triangle t) {
return 0.5 * t.getBase() * t.getHeight();
} else {
throw new IllegalArgumentException("Unknown shape: " + shape);
}
}
// â
Java 21: Same logic, cleaner with switch pattern matching
static double calculateAreaSwitch(Object shape) {
return switch (shape) {
case Circle c -> Math.PI * c.getRadius() * c.getRadius();
case Rectangle r -> r.getWidth() * r.getHeight();
case Triangle t -> 0.5 * t.getBase() * t.getHeight();
default -> throw new IllegalArgumentException("Unknown: " + shape);
};
}Bad Practices & Anti-Patterns â What Senior Developers Reject
These if-else anti-patterns are the most common reasons for failed code reviews in professional Java teams. Each pattern either reduces readability, increases complexity, or introduces subtle bugs.
Code that indents right as it grows â 4, 5, 6 levels deep â is called 'arrow code' and is virtually unreadable. Refactor using: (1) Guard clauses with early return, (2) Extract method â move nested logic to a private method, (3) Replace conditionals with polymorphism (OOP). Rule of thumb: more than 3 levels of nesting is a red flag.
A condition like 'if (a && b && !c || d && (e || f) && !g)' is a maintenance nightmare. Break complex conditions into named boolean variables or extracted methods: 'boolean isEligible = isAdult && hasIncome && !isBlacklisted;' then 'if (isEligible && hasSufficientDocuments)'. Named conditions serve as inline documentation.
Writing 'if (condition) { return true; } else { return false; }' is redundant. The condition IS the boolean value. Simply: 'return condition;'. Similarly, 'if (x > 5) { flag = true; } else { flag = false; }' should be: 'flag = (x > 5);'. This is one of the most common beginner redundancies.
When you're checking one variable against 5+ discrete values, an if-else-if ladder becomes visually cluttered. A switch statement (especially Java 14+ switch expression with arrow syntax) is dramatically cleaner. If-else should be reserved for range checks, compound boolean conditions, and null handling.
Writing the else-path first: 'if (!isValid) { handleError(); } else { processSuccess(); }' forces readers to mentally invert the logic. Put the HAPPY PATH (normal case) first, exception/error handling in else. Positive conditions are cognitively easier: 'if (isValid) { processSuccess(); } else { handleError(); }'.
An empty if block: 'if (condition) { } else { doSomething(); }' â just negate the condition: 'if (!condition) { doSomething(); }'. An empty else block: 'if (condition) { doSomething(); } else { }' â remove the empty else entirely. Empty blocks suggest incomplete logic or confusion about the intent.
// â ANTI-PATTERN 1: Returning boolean literal
public boolean isAdult(int age) {
if (age >= 18) {
return true; // â Redundant
} else {
return false; // â Redundant
}
}
// â
BETTER: Return the condition directly
public boolean isAdult(int age) {
return age >= 18;
}
// â ANTI-PATTERN 2: Overloaded god-condition
if (user != null && user.isActive() && !user.isBanned()
&& user.getRole() != null && user.getRole().hasPermission("EDIT")
&& (user.getSubscriptionLevel() == 2 || user.getSubscriptionLevel() == 3)) {
allowEdit();
}
// â
BETTER: Named boolean variables as documentation
boolean isValidUser = user != null && user.isActive() && !user.isBanned();
boolean hasEditPermission = user.getRole() != null
&& user.getRole().hasPermission("EDIT");
boolean hasPremiumAccess = user.getSubscriptionLevel() >= 2;
if (isValidUser && hasEditPermission && hasPremiumAccess) {
allowEdit();
}
// â ANTI-PATTERN 3: Inverted logic (error path first)
if (!isAuthenticated) {
redirectToLogin();
} else {
loadDashboard();
}
// â
BETTER: Happy path first
if (isAuthenticated) {
loadDashboard();
} else {
redirectToLogin();
}Real-World Production Code Examples â if-else in Context
The following examples model if-else usage in real enterprise Java codebases â Spring Boot application patterns with idiomatic conditional logic at each layer.
package com.techsustainify.payment.service;
public class PaymentProcessor {
private static final double MAX_TRANSACTION_LIMIT = 100000.00;
private static final int MAX_RETRY_ATTEMPTS = 3;
/**
* Processes a payment with full validation using guard clauses.
* Guard clause pattern: validate early, return early, happy path last.
*/
public PaymentResult processPayment(PaymentRequest request, UserAccount user) {
// Guard clause 1: Null check
if (request == null) {
return PaymentResult.failure("Payment request cannot be null");
}
// Guard clause 2: Account status
if (!user.isAccountActive()) {
return PaymentResult.failure("Account is suspended or inactive");
}
// Guard clause 3: Amount validation
if (request.getAmount() <= 0) {
return PaymentResult.failure("Payment amount must be positive");
}
// Guard clause 4: Transaction limit
if (request.getAmount() > MAX_TRANSACTION_LIMIT) {
return PaymentResult.failure("Amount exceeds transaction limit of âš" + MAX_TRANSACTION_LIMIT);
}
// Guard clause 5: Sufficient balance
if (user.getBalance() < request.getAmount()) {
return PaymentResult.failure("Insufficient balance. Available: âš" + user.getBalance());
}
// Happy path: all validations passed
// Apply discount if eligible
double finalAmount = request.getAmount();
if (user.isPremiumMember() && request.getAmount() > 5000) {
finalAmount = finalAmount * 0.95; // 5% premium discount
}
// Choose payment gateway based on amount
PaymentGateway gateway;
if (finalAmount <= 2000) {
gateway = PaymentGateway.UPI;
} else if (finalAmount <= 50000) {
gateway = PaymentGateway.NETBANKING;
} else {
gateway = PaymentGateway.RTGS;
}
return executeWithRetry(request, user, finalAmount, gateway);
}
private PaymentResult executeWithRetry(PaymentRequest request, UserAccount user,
double amount, PaymentGateway gateway) {
int attempts = 0;
PaymentResult result = null;
while (attempts < MAX_RETRY_ATTEMPTS) {
result = gateway.execute(request, amount);
if (result.isSuccess()) {
user.deductBalance(amount);
return result;
}
attempts++;
}
return PaymentResult.failure("Payment failed after " + MAX_RETRY_ATTEMPTS + " attempts");
}
}package com.techsustainify.user.validation;
import java.util.ArrayList;
import java.util.List;
public class UserValidator {
private static final int MIN_PASSWORD_LENGTH = 8;
private static final int MAX_USERNAME_LENGTH = 30;
public ValidationResult validateRegistration(UserRegistrationRequest req) {
List<String> errors = new ArrayList<>();
// Validate username
if (req.getUsername() == null || req.getUsername().isBlank()) {
errors.add("Username is required");
} else if (req.getUsername().length() > MAX_USERNAME_LENGTH) {
errors.add("Username must not exceed " + MAX_USERNAME_LENGTH + " characters");
} else if (!req.getUsername().matches("^[a-zA-Z0-9_]+$")) {
errors.add("Username can only contain letters, digits, and underscores");
}
// Validate email
if (req.getEmail() == null || req.getEmail().isBlank()) {
errors.add("Email address is required");
} else if (!req.getEmail().contains("@") || !req.getEmail().contains(".")) {
errors.add("Please enter a valid email address");
}
// Validate password
if (req.getPassword() == null || req.getPassword().length() < MIN_PASSWORD_LENGTH) {
errors.add("Password must be at least " + MIN_PASSWORD_LENGTH + " characters");
} else if (!req.getPassword().matches(".*[A-Z].*")) {
errors.add("Password must contain at least one uppercase letter");
} else if (!req.getPassword().matches(".*[0-9].*")) {
errors.add("Password must contain at least one digit");
}
// Validate age
if (req.getAge() < 13) {
errors.add("You must be at least 13 years old to register");
} else if (req.getAge() > 120) {
errors.add("Please enter a valid age");
}
return errors.isEmpty()
? ValidationResult.success()
: ValidationResult.failure(errors);
}
}if-else Flowchart â Visual Decision Flow
These flowcharts show the execution paths for each type of if-else construct in Java.
Code Execution Flow â from source to output
Java if-else Interview Questions â Beginner to Advanced
These questions are consistently asked in Java fresher interviews, OCPJP/OCA certification exams, and campus placement tests.
Practice Questions â Test Your if-else Knowledge
Challenge yourself with these practice questions. Attempt each independently before reading the answer â active recall is proven to be 2â3x more effective than passive reading.
1. What is the output of the following code? int x = 15; if (x > 10) System.out.println("Greater than 10"); System.out.println("This always prints"); if (x > 20) System.out.println("Greater than 20"); System.out.println("Done");
Easy2. Rewrite using ternary operator: String result; if (score >= 50) { result = "PASS"; } else { result = "FAIL"; }
Easy3. Find and fix the bug: String input = getUserInput(); if (input == "quit") { System.out.println("Exiting..."); System.exit(0); }
Easy4. Refactor this nested code using guard clauses: public void processOrder(Order order) { if (order != null) { if (order.isConfirmed()) { if (order.getItems().size() > 0) { if (order.getPaymentStatus() == PAID) { shipOrder(order); } } } } }
Medium5. What is the output? int a = 5, b = 3; if (a > b) if (a > 10) System.out.println("A"); else System.out.println("B"); System.out.println("C");
Medium6. Simplify this code: public boolean isEligibleForDiscount(Customer c) { if (c.isPremium() == true) { if (c.getAge() >= 60 || c.getAge() <= 25) { return true; } else { return false; } } else { return false; } }
Medium7. Using Java 16+ pattern matching, rewrite: Object obj = getShape(); if (obj instanceof Rectangle) { Rectangle r = (Rectangle) obj; System.out.println(r.getWidth() * r.getHeight()); } else if (obj instanceof Circle) { Circle c = (Circle) obj; System.out.println(Math.PI * c.getRadius() * c.getRadius()); }
Medium8. Will this compile? What is its output? boolean flag = false; if (flag = true) { System.out.println("Yes"); } else { System.out.println("No"); }
HardConclusion â if-else: The Decision Engine of Every Java Program
The if-else statement is the heartbeat of program logic. Every meaningful program makes decisions â checking user permissions, validating inputs, branching on data values, handling errors. All of these flow through if-else constructs. Mastering if-else is not just about syntax â it is about writing clear, correct, and maintainable conditional logic.
The difference between a junior and senior Java developer is often visible in how they use conditionals. Junior code has deeply nested arrow code, redundant boolean literals, missing braces, and == for String comparison. Senior code uses guard clauses, named conditions, .equals() consistently, appropriate ternary, and Java 16+ pattern matching where it improves clarity.
Your next step: Java switch Statement â where you'll see how Java provides an alternative to if-else-if ladders for multi-way branching, and how the modern switch expression (Java 14+) and pattern matching switch (Java 21) make it even more powerful. â