Java tutorials  /  Java If-Else Statements
Chapter 4 · Java

Java If-Else Statements

The if-else statement is a conditional control flow structure in Java that allows a program to execute one block of code if a specified boolean condition is true, and optionally execute an alternative block of code if the condition is false. Java supports simple if, if-else, else-if ladders, and nested if statements to handle multiple decision paths.

Think of an if-else statement like a fork in the road while driving. If a sign says 'Turn left if the bridge is open', you check the condition (is the bridge open?), and based on true or false, you take one of two distinct paths. Your program does the same thing: it checks a condition, and depending on whether it's true or false, follows a different set of instructions.

Consider an online food delivery app determining shipping charges. The app checks: if the order total is above a certain threshold, shipping is free; else if the customer has a premium membership, shipping is discounted; else, standard shipping charges apply. This chain of decisions, implemented using an if-else-if ladder, is exactly how real e-commerce platforms like Amazon or Swiggy calculate final costs at checkout, adjusting dynamically based on multiple business rules evaluated in a specific priority order.

Programs need to make decisions and behave differently based on varying input or state — a program that always does the exact same thing regardless of circumstances has very limited real-world use. If-else statements provide this essential decision-making capability, allowing programs to validate user input, implement business rules, handle different cases (like error conditions vs. success conditions), and create dynamic, responsive behavior based on data that isn't known until the program actually runs.

  • Simple if Statement: Executes a block of code only if a single condition evaluates to true; if false, the block is simply skipped with no alternative action taken.
  • if-else Statement: Provides exactly two paths: one block executes if the condition is true, and a different block executes if the condition is false, ensuring one of the two paths always runs.
  • else-if Ladder: Chains multiple conditions together to check several mutually exclusive cases in sequence, stopping and executing the corresponding block as soon as the first true condition is found.
  • Nested if Statement: An if or if-else statement placed inside another if or else block, used when a decision depends on the outcome of a previous, outer condition being true first.
if (condition) { // executes if condition is true } else if (anotherCondition) { // executes if anotherCondition is true } else { // executes if all above conditions are false }
A beginner needs to write a program that categorizes a student's exam score into a letter grade (A, B, C, or F) based on different score ranges, requiring multiple conditions to be checked in a specific priority order using an else-if ladder.
Grading System Using if-else-if Ladder
This example checks a student's score against multiple thresholds in sequence to determine the appropriate letter grade, demonstrating a classic else-if ladder pattern.
Java
public class GradeSystem { public static void main(String[] args) { int score = 82; char grade; if (score >= 90) { grade = 'A'; } else if (score >= 75) { grade = 'B'; } else if (score >= 60) { grade = 'C'; } else { grade = 'F'; } System.out.println("Score: " + score); System.out.println("Grade: " + grade); } }
Score: 82 Grade: B
Java evaluates each condition from top to bottom in order. Since 'score' (82) is not >= 90, the first condition is false, so Java moves to the next 'else if'. Since 82 >= 75 is true, 'grade' is set to 'B', and Java skips all remaining else-if and else blocks entirely, even though 82 also technically satisfies the '>= 60' condition further down.
Nested if Statement for Eligibility Check
This example demonstrates a nested if statement, where an inner condition is only checked after an outer condition has already been confirmed true, modeling a loan eligibility check.
Java
public class LoanEligibility { public static void main(String[] args) { int age = 25; int creditScore = 720; if (age >= 18) { if (creditScore >= 700) { System.out.println("Loan Approved"); } else { System.out.println("Loan Denied: Insufficient Credit Score"); } } else { System.out.println("Loan Denied: Applicant is a Minor"); } } }
Loan Approved
The outer 'if (age >= 18)' is checked first; since 'age' is 25, this condition is true, so Java enters this block and proceeds to check the inner nested condition. Only then is 'creditScore >= 700' evaluated; since it's true, 'Loan Approved' is printed. If the outer condition had been false, the inner nested if-else would never even be evaluated, regardless of the credit score value.
  • Adding a Semicolon Immediately After the if Condition: Writing 'if (score >= 90); { grade = 'A'; }' with a semicolon right after the condition creates an empty statement as the 'if' body. The code block in curly braces then executes unconditionally every time, regardless of whether the condition was true or false, since it's no longer actually linked to the if statement.
  • Incorrect Ordering in an else-if Ladder: Writing conditions from lowest to highest (e.g., checking 'score >= 60' before 'score >= 90') causes higher grade thresholds to never be reached, since a score of 95 would incorrectly match the very first true condition ('>= 60') and stop there. Ranges in an else-if ladder must be ordered from most restrictive/highest to least restrictive/lowest when checking with '>=' comparisons.
  • Using Assignment (=) Instead of Equality (==) in a Condition: Writing 'if (isValid = true)' instead of 'if (isValid == true)' assigns the value 'true' to 'isValid' rather than comparing it, making the condition always evaluate to true regardless of the variable's original value — a subtle bug that silently alters program state.
  • Overusing Deeply Nested if Statements: Nesting if statements 4 or 5 levels deep creates code that is extremely difficult to read, test, and debug (sometimes called the 'arrow anti-pattern' due to the visual indentation shape). This should be refactored using early returns, combined logical conditions ('&&', '||'), or separate helper methods.
  • Always Use Curly Braces, Even for Single Statements: Even though Java allows omitting curly braces for a single-statement if block, always include them. This prevents a common bug where a developer later adds a second statement intending it to be part of the conditional block, but it silently executes unconditionally since only the first statement was actually governed by the if.
  • Order else-if Conditions from Most to Least Specific: When checking numeric ranges with '>=' or '<=', always order conditions from the highest/most restrictive threshold down to the lowest, ensuring each score or value is correctly categorized into the first matching, most appropriate range.
  • Use Early Returns to Reduce Nesting in Methods: Instead of deeply nesting if-else blocks inside a method, use early 'return' statements for invalid or edge cases at the top of the method. This flattens the code structure, making the main logic path clearer and easier to follow than deeply indented nested conditions.
  • Consider a Switch Statement for Many Discrete Value Checks: When checking a single variable against many specific, discrete values (rather than ranges), a 'switch' statement is often cleaner and more readable than a long else-if ladder, and can also be more performant for certain use cases due to how the JVM can optimize switch statements.
What happens if you omit curly braces in an if statement with multiple lines of code intended to run conditionally?
If curly braces are omitted, Java's if statement only applies to the single statement immediately following it. Any additional lines below, even if visually indented to look like they belong to the if block, are treated as regular unconditional code that always executes. For example, in 'if (x > 0) System.out.println("positive"); System.out.println("done");', the second println always executes regardless of the condition, since only the first statement is actually part of the if block, which can lead to subtle and hard-to-spot logic bugs.
In an else-if ladder, does Java evaluate every condition even after one has already matched?
No. Once Java finds a condition in an else-if ladder that evaluates to true, it executes that corresponding block and then skips all subsequent else-if and else blocks entirely, without even evaluating their conditions. This is why the order of conditions matters significantly, especially with overlapping numeric ranges — placing a broader condition before a more specific one can cause the specific case to never be reached.
What is the difference between using a nested if statement and combining conditions with the '&&' logical operator? When would you prefer one over the other?
A nested if statement checks conditions sequentially in separate blocks, allowing different 'else' logic to be attached at each level (e.g., a different error message for each failed condition). Combining conditions with '&&' evaluates both conditions as a single combined boolean expression, executing a block only if all conditions are true, but offering only one generic 'else' path for any failure. Nested ifs are preferable when you need distinct handling or specific error messages for each individual condition's failure; combined '&&' conditions are preferable when you only care whether all conditions pass or fail together, without needing to distinguish which specific condition caused a failure.
Write a Java program that checks if a given number is positive, negative, or zero, and prints the appropriate message.
public class NumberCheck { public static void main(String[] args) { int number = -7; if (number > 0) { System.out.println("Positive"); } else if (number < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); } } } // Output: // Negative
Identify the bug in the following code and explain what it will actually print: int age = 15; if (age >= 18); { System.out.println("Adult"); }
The bug is the semicolon placed immediately after 'if (age >= 18)'. This creates an empty statement as the entire body of the if statement, meaning the condition check does nothing at all. The curly-braced block containing 'System.out.println("Adult");' is now just a standalone code block, completely disconnected from the if condition, so it executes unconditionally every time. Despite 'age' being 15 (a minor), the program will still print 'Adult', which is the opposite of the intended behavior. The fix is to remove the semicolon: 'if (age >= 18) { System.out.println("Adult"); }'.
Write a nested if statement that checks if a person is eligible to vote (age >= 18) AND is a registered citizen (isRegistered == true), printing distinct messages for each specific failure reason.
public class VotingEligibility { public static void main(String[] args) { int age = 20; boolean isRegistered = false; if (age >= 18) { if (isRegistered) { System.out.println("Eligible to Vote"); } else { System.out.println("Not Eligible: Not a Registered Citizen"); } } else { System.out.println("Not Eligible: Under 18 Years of Age"); } } } // Output: // Not Eligible: Not a Registered Citizen

If-else statements are the foundational decision-making structures in Java, allowing programs to execute different code paths based on boolean conditions. Mastering simple if, if-else, else-if ladders, and nested if statements — while avoiding common pitfalls like misplaced semicolons and incorrect condition ordering — is essential for implementing real-world business logic, input validation, and dynamic program behavior.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.