If Else in Java — Conditional Statements Tutorial
Chapter 03 · Java Programming Series
PBA Institute 11 min read Beginner 2024

If Else Decision Making

Decision making is the heart of programming. In Java, the if-else statement lets a program take different paths based on conditions. Combined with logical operators it becomes a powerful tool for solving real-world problems such as login checks, eligibility tests, grade calculations and more.

Key Features

Simple If

Executes a block only when a condition is true.

🔀

If-Else

Runs one of two blocks depending on the condition.

🧩

Else-If Ladder

Tests multiple conditions one after another.

🪆

Nested If

An if statement inside another if statement.

⚖️

Ternary Operator

A compact one-line form of if-else expressed as ?:.

🧠

Logical Combos

Combine conditions using &&, || and !.

Syntax

  • if (condition) { /* statements */ }
  • if-else: if (cond) { … } else { … }
  • else-if: use multiple else if blocks before a final else.
  • Conditions return a booleantrue or false.

Comparison Operators

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal5 != 3true
>Greater than7 > 4true
<Less than2 < 9true
>=Greater or equal5 >= 5true
<=Less or equal4 <= 6true

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind If Else in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Simple If-Else
class Main
{
    public static void main(String args[])
    {
        int age = 20;

        if (age >= 18)
        {
            System.out.println("You can vote");
        }
        else
        {
            System.out.println("Not eligible");
        }
    }
}
Output You can vote

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Largest of Two Numbers
class Main
{
    public static void main(String args[])
    {
        int a = 25, b = 14;

        if (a > b)
            System.out.println(a + " is larger");
        else
            System.out.println(b + " is larger");
    }
}
Output 25 is larger
Even or Odd
class Main
{
    public static void main(String args[])
    {
        int n = 7;

        if (n % 2 == 0)
            System.out.println(n + " is even");
        else
            System.out.println(n + " is odd");
    }
}
Output 7 is odd
Grade with Else-If Ladder
class Main
{
    public static void main(String args[])
    {
        int marks = 76;

        if (marks >= 90)       System.out.println("A+");
        else if (marks >= 80)  System.out.println("A");
        else if (marks >= 70)  System.out.println("B");
        else if (marks >= 60)  System.out.println("C");
        else                   System.out.println("F");
    }
}
Output B
Nested If — Largest of Three
class Main
{
    public static void main(String args[])
    {
        int a = 10, b = 25, c = 18;

        if (a > b)
        {
            if (a > c)
                System.out.println("a is largest");
            else
                System.out.println("c is largest");
        }
        else
        {
            if (b > c)
                System.out.println("b is largest");
            else
                System.out.println("c is largest");
        }
    }
}
Output b is largest
Ternary Operator
class Main
{
    public static void main(String args[])
    {
        int n = 12;

        String type = (n % 2 == 0) ? "Even" : "Odd";

        System.out.println(type);
    }
}
Output Even

Notes & Tips

  • Curly braces { } are optional for a single statement but recommended for readability.
  • Always use == for comparison and = for assignment — a common beginner bug.
  • Compare strings with equals(), not ==.
  • Use the ternary operator only for short, simple conditions.
  • Indent your code consistently — it makes nested ifs far easier to read.

Real-World Use Cases

Login Systems

Compare entered password with stored value before granting access.

Grade Reports

Convert numeric marks into A/B/C grades using else-if ladders.

Discount Logic

Apply different discount percentages based on cart value.

Traffic Signals

Decide signal color based on time of day or sensor data.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Check whether a number entered by user is positive, negative or zero.
  • Q2. Find the largest of three numbers using nested if.
  • Q3. Check if a year is a leap year.
  • Q4. Determine if a triangle is equilateral, isosceles or scalene.
  • Q5. Print whether a character is a vowel or consonant.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 What is the difference between if-else and switch?
if-else can use any boolean expression, while switch only works on int, char, String, byte, short and enums.
Q2 Can we use a String in an if condition?
Yes — compare with .equals() and use the result in the if condition.
Q3 What is short-circuit evaluation?
When using && or ||, Java stops evaluating once the result is known — it skips the rest of the expression.
Q4 Is else mandatory after if?
No, else is optional. You can use an if without an else block.
Q5 What does the ternary operator do?
It returns one of two values based on a condition in a single expression — cond ? a : b.

FAQ

FAQ 1 Can an if statement be nested inside another if?
Yes, you can nest if statements to any depth, though deep nesting hurts readability — prefer else-if ladders or methods.
FAQ 2 Why use braces for single-statement ifs?
Braces prevent bugs when you later add a second statement and forget to add them, like Apple's infamous goto fail bug.
FAQ 3 Can I assign inside an if?
Java does not allow if (x = 5) because assignment returns int which is not a boolean — this protects from common bugs.
FAQ 4 Are if-else and switch interchangeable?
Not always. Use switch for many equality checks on the same variable; use if-else for ranges and complex boolean logic.
FAQ 5 Is there a limit on else-if blocks?
No, but more than 5–6 usually means you should refactor into a switch, a map or a polymorphic design.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with If Else in Java:

  • Forgetting the semicolon ; at the end of statements while using If Else.
  • Mixing up similar method names — read Java docs before using new APIs related to If Else.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
User Input Loops OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving If Else — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
If ElseIf Else conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV User Input — strengthens your understanding of the previous building block.
NEXT Loops — the natural progression after mastering If Else.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

if, if-else, else-if and nested forms allow Java programs to make decisions. Combine them with logical operators for powerful branching logic. Always use braces for clarity, prefer the ternary operator for short cases, and refactor deeply nested ifs into methods or a switch when possible.

Continue Learning