LearnContact
Lesson 1255 min read

Conditional Statements in Java

Learn how Java programs make decisions using if, if-else, else-if, nested conditions, switch statements, switch expressions, logical operators, and real-world decision-making programs.

Introduction

In the previous lesson, you learned how Java programs receive input and display output. However, most useful programs must do more than simply execute every statement from top to bottom.

Programs need to make decisions. A banking application decides whether a withdrawal is allowed. A login system decides whether credentials are correct. An online store decides whether a customer receives a discount.

Conditional statements allow a Java program to execute different blocks of code depending on whether specific conditions are true or false.

Simple Decision
int age = 20;

if (age >= 18) {
    System.out.println(
            "You are eligible to vote."
    );
} else {
    System.out.println(
            "You are not eligible to vote."
    );
}
Decision Flow
CONDITION

age >= 18

    │
    ▼

TRUE OR FALSE?

   / \
  /   \

TRUE   FALSE

 │       │
 ▼       ▼

ALLOW   DENY
What You Will Learn
  • What conditional statements are.
  • Why programs need decision-making.
  • How boolean conditions control program flow.
  • How the if statement works.
  • How the if-else statement works.
  • How the else-if ladder works.
  • How nested if statements work.
  • How independent if statements differ from else-if.
  • How relational operators are used in conditions.
  • How logical AND combines requirements.
  • How logical OR combines alternatives.
  • How logical NOT reverses conditions.
  • How short-circuit evaluation works.
  • How to compare Strings correctly.
  • How to compare characters.
  • How to handle floating-point comparisons.
  • How the ternary operator works.
  • When to use if-else instead of ternary.
  • How the traditional switch statement works.
  • Why break is important in traditional switch statements.
  • What fall-through behavior means.
  • How the default case works.
  • How to combine multiple case labels.
  • Which data types switch supports.
  • How modern switch expressions work.
  • How arrow case labels work.
  • How switch expressions return values.
  • How the yield keyword works.
  • The difference between traditional and modern switch.
  • When to use if-else and when to use switch.
  • How to build real-world decision-making programs.
  • Common conditional statement errors.
  • Best practices for readable decision logic.

What are Conditional Statements?

Conditional statements are programming structures that control which code executes based on the result of a condition.

Conditional Execution
WITHOUT CONDITIONS

Statement 1
    │
    ▼
Statement 2
    │
    ▼
Statement 3


WITH CONDITIONS

        Condition
        /       \
     true       false
       │           │
       ▼           ▼
   Action A     Action B

A condition in Java must produce a boolean result: true or false.

Boolean Conditions
10 > 5       // true

20 == 10     // false

18 >= 18     // true

7 != 7       // false

Why Conditions are Needed

Authentication

Check whether usernames, passwords, permissions, and security requirements are valid.

Transactions

Approve or reject payments based on balances, limits, and account status.

Discounts

Apply different prices depending on membership, order value, or promotional rules.

Games

Control player health, scores, levels, collisions, and winning conditions.

Classification

Categorize marks, ages, temperatures, ratings, and other values.

Application Logic

Execute different features according to user choices and application state.

Real-World Analogy

Imagine entering a cinema where the ticket price depends on your age.

Cinema Decision
CHECK AGE

    │
    ▼

Age < 5?

 /     \
YES     NO
 │       │
 ▼       ▼
FREE   Check next rule

          │
          ▼

      Age < 18?

       /     \
     YES      NO
      │        │
      ▼        ▼
   CHILD     ADULT
   TICKET    TICKET

Java conditional statements work in the same way. Conditions are checked, and the program chooses the appropriate path.

Decision-Making Process

General Decision Process
1. RECEIVE DATA

       │
       ▼

2. EVALUATE CONDITION

       │
       ▼

3. CONDITION RESULT

      / \
     /   \

  TRUE   FALSE

    │       │
    ▼       ▼

4. EXECUTE APPROPRIATE CODE

       │
       ▼

5. CONTINUE PROGRAM

Types of Conditional Statements

Java Decision Structures
CONDITIONAL STATEMENTS

├── if
│
├── if-else
│
├── else-if Ladder
│
├── Nested if
│
├── Ternary Operator
│
├── Traditional switch
│
└── Modern switch Expression

Boolean Conditions

Java conditional statements require boolean expressions. The condition must evaluate to either true or false.

Valid Conditions
int age = 20;

boolean active = true;

if (age >= 18) {
    System.out.println("Adult");
}

if (active) {
    System.out.println("Account active");
}
Invalid Condition
int number = 10;

// Invalid in Java:
// if (number) {
//     System.out.println("Valid");
// }
Java Requires boolean Conditions
  • Java does not automatically treat non-zero integers as true.
  • Java does not automatically treat zero as false.
  • The condition inside if must evaluate to boolean.
  • This differs from languages such as C and JavaScript.

if Statement

The if statement executes a block of code only when its condition is true.

if Statement Syntax

Syntax
if (condition) {

    // Executes only when
    // condition is true

}

How if Works

if Flow
START

  │
  ▼

CHECK CONDITION

  │
  ├── true ──────► Execute if block
  │                      │
  │                      ▼
  │                   Continue
  │
  └── false ───────────► Skip block
                         │
                         ▼
                      Continue

Simple if Example

Temperature Check
int temperature = 35;

if (temperature > 30) {

    System.out.println(
            "It is a hot day."
    );

}
Output
It is a hot day.

if with Variables

Balance Check
double balance = 5000;
double withdrawal = 2000;

if (balance >= withdrawal) {

    System.out.println(
            "Sufficient balance."
    );

}

if with User Input

User Input Condition
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter your age: "
        );

        int age =
                scanner.nextInt();

        if (age >= 18) {

            System.out.println(
                    "You are an adult."
            );

        }

    }
}

Multiple Statements inside if

Multiple Statements
int marks = 85;

if (marks >= 75) {

    System.out.println(
            "Excellent performance."
    );

    System.out.println(
            "You earned a distinction."
    );

    System.out.println(
            "Keep up the good work."
    );

}

if without Braces

Java allows braces to be omitted when the if statement controls exactly one statement.

Without Braces
int age = 20;

if (age >= 18)
    System.out.println("Adult");
Dangerous Example
int age = 15;

if (age >= 18)
    System.out.println("Adult");

    System.out.println(
            "Access granted"
    );

Only the first statement belongs to the if statement. The second statement executes regardless of the condition.

Prefer Braces
  • Braces clearly show which statements belong to the condition.
  • They reduce bugs when new statements are added later.
  • They improve readability.
  • Consistent braces are recommended even for one-line conditions.

if-else Statement

The if-else statement chooses between two alternative blocks of code.

if-else Syntax

Syntax
if (condition) {

    // Executes when true

} else {

    // Executes when false

}

How if-else Works

if-else Flow
        CONDITION

           │
           ▼

      TRUE OR FALSE?

        /       \
       /         \

    TRUE         FALSE

      │             │
      ▼             ▼

  IF BLOCK      ELSE BLOCK

      │             │
      └──────┬──────┘
             │
             ▼

          CONTINUE

Even or Odd Example

Even or Odd
int number = 17;

if (number % 2 == 0) {

    System.out.println(
            "Even number"
    );

} else {

    System.out.println(
            "Odd number"
    );

}

Voting Eligibility

Voting Check
int age = 17;

if (age >= 18) {

    System.out.println(
            "Eligible to vote."
    );

} else {

    System.out.println(
            "Not eligible to vote."
    );

}

Positive or Negative

Number Check
int number = -25;

if (number >= 0) {

    System.out.println(
            "Non-negative number"
    );

} else {

    System.out.println(
            "Negative number"
    );

}
What about Zero?
  • Zero is neither positive nor negative.
  • The previous example classifies zero as non-negative.
  • Use an else-if ladder when positive, negative, and zero must be separate categories.

else-if Ladder

An else-if ladder checks multiple conditions in sequence. The first condition that evaluates to true executes its block, and the remaining conditions are skipped.

else-if Syntax

Syntax
if (condition1) {

    // First condition is true

} else if (condition2) {

    // Second condition is true

} else if (condition3) {

    // Third condition is true

} else {

    // No condition was true

}

How else-if Works

else-if Flow
CONDITION 1?

  ├── true ──► BLOCK 1 ──► END
  │
  └── false
        │
        ▼

CONDITION 2?

  ├── true ──► BLOCK 2 ──► END
  │
  └── false
        │
        ▼

CONDITION 3?

  ├── true ──► BLOCK 3 ──► END
  │
  └── false
        │
        ▼

     ELSE BLOCK

Grade Calculator

Grade Classification
int marks = 82;

if (marks >= 90) {

    System.out.println("Grade A+");

} else if (marks >= 80) {

    System.out.println("Grade A");

} else if (marks >= 70) {

    System.out.println("Grade B");

} else if (marks >= 60) {

    System.out.println("Grade C");

} else if (marks >= 40) {

    System.out.println("Grade D");

} else {

    System.out.println("Failed");

}

Number Classification

Positive, Negative, or Zero
int number = 0;

if (number > 0) {

    System.out.println("Positive");

} else if (number < 0) {

    System.out.println("Negative");

} else {

    System.out.println("Zero");

}

Age Category

Age Classification
int age = 35;

if (age < 0) {

    System.out.println(
            "Invalid age"
    );

} else if (age <= 12) {

    System.out.println(
            "Child"
    );

} else if (age <= 19) {

    System.out.println(
            "Teenager"
    );

} else if (age <= 59) {

    System.out.println(
            "Adult"
    );

} else {

    System.out.println(
            "Senior citizen"
    );

}

Order of Conditions

The order of conditions is extremely important because an else-if ladder stops after the first true condition.

Wrong Order
int marks = 95;

if (marks >= 40) {

    System.out.println("Pass");

} else if (marks >= 90) {

    System.out.println("Excellent");

}
Output
Pass
Correct Order
int marks = 95;

if (marks >= 90) {

    System.out.println("Excellent");

} else if (marks >= 40) {

    System.out.println("Pass");

} else {

    System.out.println("Fail");

}
Check Specific Conditions First
  • Conditions in an else-if ladder are checked from top to bottom.
  • The first true condition wins.
  • Later conditions are not checked after a match.
  • For overlapping numeric ranges, ordering is critical.

Independent if Statements

Multiple independent if statements are all checked separately.

Independent Conditions
int number = 12;

if (number > 0) {
    System.out.println("Positive");
}

if (number % 2 == 0) {
    System.out.println("Even");
}

if (number > 10) {
    System.out.println("Greater than 10");
}
Output
Positive
Even
Greater than 10

Independent if vs else-if

Comparison
MULTIPLE if STATEMENTS

Every condition is checked

Condition 1 ──► Check
Condition 2 ──► Check
Condition 3 ──► Check

Multiple blocks can execute


else-if LADDER

Conditions checked in order

First true condition
        │
        ▼
Execute one block
        │
        ▼
Skip remaining conditions

Nested if Statement

A nested if statement places one conditional statement inside another conditional block.

Nested if Syntax

Syntax
if (condition1) {

    if (condition2) {

        // Executes when both
        // conditions are true

    }

}

Login Example

Nested Login Validation
String username = "admin";
String password = "java123";

if (username.equals("admin")) {

    if (password.equals("java123")) {

        System.out.println(
                "Login successful"
        );

    } else {

        System.out.println(
                "Incorrect password"
        );

    }

} else {

    System.out.println(
            "Unknown username"
    );

}

Loan Eligibility

Nested Eligibility Check
int age = 30;
double salary = 50000;
int creditScore = 750;

if (age >= 21) {

    if (salary >= 30000) {

        if (creditScore >= 700) {

            System.out.println(
                    "Loan approved"
            );

        } else {

            System.out.println(
                    "Credit score too low"
            );

        }

    } else {

        System.out.println(
                "Salary requirement not met"
        );

    }

} else {

    System.out.println(
            "Age requirement not met"
    );

}

Nested if vs Logical Operators

Nested Version
if (age >= 18) {

    if (hasId) {

        System.out.println(
                "Entry allowed"
        );

    }

}
Logical AND Version
if (age >= 18 && hasId) {

    System.out.println(
            "Entry allowed"
    );

}

Logical operators are often clearer when all conditions simply need to be true. Nested conditions are useful when different failure points require different actions or messages.

Relational Operators in Conditions

Relational Operators
OPERATOR    MEANING

==          Equal to

!=          Not equal to

>           Greater than

<           Less than

>=          Greater than or equal to

<=          Less than or equal to
Examples
int age = 25;

if (age == 25) {
    System.out.println("Exactly 25");
}

if (age != 18) {
    System.out.println("Not 18");
}

if (age > 20) {
    System.out.println("Greater than 20");
}

if (age <= 30) {
    System.out.println("30 or younger");
}

Logical AND (&&)

The logical AND operator returns true only when both conditions are true.

AND Example
int age = 25;
boolean hasLicense = true;

if (age >= 18 && hasLicense) {

    System.out.println(
            "You can drive."
    );

}
AND Truth Table
A       B       A && B

true    true    true

true    false   false

false   true    false

false   false   false

Logical OR (||)

The logical OR operator returns true when at least one condition is true.

OR Example
boolean isAdmin = false;
boolean isManager = true;

if (isAdmin || isManager) {

    System.out.println(
            "Access granted."
    );

}
OR Truth Table
A       B       A || B

true    true    true

true    false   true

false   true    true

false   false   false

Logical NOT (!)

The logical NOT operator reverses a boolean value.

NOT Example
boolean loggedIn = false;

if (!loggedIn) {

    System.out.println(
            "Please log in."
    );

}
NOT Results
!true   → false

!false  → true

Combining Multiple Conditions

Complex Condition
int age = 25;
boolean hasTicket = true;
boolean banned = false;

if (
    age >= 18
    && hasTicket
    && !banned
) {

    System.out.println(
            "Entry allowed"
    );

}
Grouped Conditions
boolean isAdmin = false;
boolean isManager = true;
boolean active = true;

if (
    (isAdmin || isManager)
    && active
) {

    System.out.println(
            "Management access granted"
    );

}

Operator Precedence in Conditions

Logical operators have different precedence. Parentheses should be used when grouping is important or when they improve readability.

Common Logical Precedence
HIGHER

!

&&

||

LOWER
Use Parentheses
if (
    (isAdmin || isManager)
    && accountActive
) {

    System.out.println(
            "Access granted"
    );

}

Short-Circuit Evaluation

The && and || operators may skip evaluation of the second operand when the final result is already known.

Safe Division Check
int divisor = 0;

if (
    divisor != 0
    && 100 / divisor > 5
) {

    System.out.println(
            "Condition true"
    );

}

Because divisor != 0 is false, Java does not evaluate 100 / divisor > 5. This prevents division by zero.

Short-Circuit Logic
A && B

If A is false:

Result is already false

B is skipped


A || B

If A is true:

Result is already true

B is skipped

String Comparison

Strings should usually be compared using equals() or equalsIgnoreCase(), not ==.

Incorrect String Comparison
String first =
        new String("Java");

String second =
        new String("Java");

System.out.println(
        first == second
);

// false
Correct String Comparison
System.out.println(
        first.equals(second)
);

// true
== vs equals()
  • == compares object references for objects.
  • equals() compares String content.
  • Two different String objects can contain the same text.
  • Use equals() when comparing String values.

equals() Method

Login Comparison
String username = "admin";

if (username.equals("admin")) {

    System.out.println(
            "Welcome, Administrator"
    );

}
Null-Safe Constant Comparison
String role = null;

if ("admin".equals(role)) {

    System.out.println(
            "Administrator"
    );

}

Calling equals() on a known non-null constant can prevent NullPointerException when the variable might be null.

equalsIgnoreCase()

Case-Insensitive Comparison
String answer = "YES";

if (answer.equalsIgnoreCase("yes")) {

    System.out.println(
            "Confirmed"
    );

}

Comparing char Values

Character Comparison
char grade = 'A';

if (grade == 'A') {

    System.out.println(
            "Excellent"
    );

}
char Comparison
  • char is a primitive data type.
  • Primitive char values can be compared using ==.
  • Use single quotes for character literals.
  • Character comparison is case-sensitive.

Comparing Floating-Point Values

Direct equality comparison of calculated floating-point values can be unreliable because many decimal values cannot be represented exactly in binary.

Potential Problem
double result =
        0.1 + 0.2;

System.out.println(
        result == 0.3
);

// May print false
Tolerance Comparison
double result =
        0.1 + 0.2;

double expected =
        0.3;

double tolerance =
        0.000001;

if (
    Math.abs(result - expected)
    < tolerance
) {

    System.out.println(
            "Values are approximately equal"
    );

}

Ternary Operator

The ternary operator is a compact conditional expression that selects one of two values.

Ternary Operator Syntax

Syntax
condition
    ? valueWhenTrue
    : valueWhenFalse
Ternary Flow
CONDITION

   / \
TRUE FALSE

 │     │
 ▼     ▼

VALUE  VALUE
  A      B

   \    /
    \  /
   RESULT

Ternary Examples

Adult or Minor
int age = 20;

String status =
        age >= 18
        ? "Adult"
        : "Minor";

System.out.println(status);
Maximum Value
int first = 10;
int second = 20;

int maximum =
        first > second
        ? first
        : second;

System.out.println(maximum);
Even or Odd
int number = 15;

String result =
        number % 2 == 0
        ? "Even"
        : "Odd";

System.out.println(result);

Nested Ternary Operator

Nested Ternary
int number = 0;

String result =
        number > 0
        ? "Positive"
        : number < 0
            ? "Negative"
            : "Zero";

System.out.println(result);
Avoid Complex Nested Ternary Expressions
  • Nested ternary expressions can quickly become difficult to read.
  • Use them only for simple value selection.
  • Use if-else when multiple steps or complex conditions are involved.
  • Readability is more important than reducing line count.

if-else vs Ternary Operator

Comparison
if-else

Best for:
Multiple statements
Complex logic
Detailed branching
Different actions


Ternary

Best for:
Simple value selection
Short conditions
Assignments
Compact expressions

switch Statement

The switch statement selects one execution path by comparing one expression against multiple case labels.

Traditional switch Syntax

Syntax
switch (expression) {

    case value1:
        // Statements
        break;

    case value2:
        // Statements
        break;

    default:
        // Statements

}

How switch Works

switch Flow
SWITCH VALUE

      │
      ▼

MATCH CASE?

 ├── Case 1 ──► Action 1
 │
 ├── Case 2 ──► Action 2
 │
 ├── Case 3 ──► Action 3
 │
 └── No Match ─► default

Basic switch Example

Day Number
int day = 3;

switch (day) {

    case 1:
        System.out.println("Monday");
        break;

    case 2:
        System.out.println("Tuesday");
        break;

    case 3:
        System.out.println("Wednesday");
        break;

    case 4:
        System.out.println("Thursday");
        break;

    case 5:
        System.out.println("Friday");
        break;

    case 6:
        System.out.println("Saturday");
        break;

    case 7:
        System.out.println("Sunday");
        break;

    default:
        System.out.println(
                "Invalid day"
        );

}

break Statement

In a traditional switch statement, break exits the switch after a matching case finishes.

Using break
int choice = 2;

switch (choice) {

    case 1:
        System.out.println("Add");
        break;

    case 2:
        System.out.println("Edit");
        break;

    case 3:
        System.out.println("Delete");
        break;

}

Fall-Through Behavior

Without break, execution continues into following case blocks in a traditional switch statement.

Fall-Through Example
int number = 1;

switch (number) {

    case 1:
        System.out.println("One");

    case 2:
        System.out.println("Two");

    case 3:
        System.out.println("Three");

}
Output
One
Two
Three
Traditional switch Fall-Through
  • A matching case starts execution.
  • Without break, later case statements also execute.
  • Fall-through can be intentional but often causes beginner bugs.
  • Modern arrow-style switch cases do not fall through.

default Case

Default Example
int month = 15;

switch (month) {

    case 1:
        System.out.println("January");
        break;

    case 2:
        System.out.println("February");
        break;

    default:
        System.out.println(
                "Invalid month"
        );

}

Multiple Case Labels

Traditional Grouped Cases
int day = 6;

switch (day) {

    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        System.out.println("Weekday");
        break;

    case 6:
    case 7:
        System.out.println("Weekend");
        break;

    default:
        System.out.println("Invalid day");

}

switch with char

Character Menu
char grade = 'A';

switch (grade) {

    case 'A':
        System.out.println("Excellent");
        break;

    case 'B':
        System.out.println("Good");
        break;

    case 'C':
        System.out.println("Average");
        break;

    default:
        System.out.println("Unknown grade");

}

switch with String

Role Check
String role = "admin";

switch (role) {

    case "admin":
        System.out.println(
                "Full access"
        );
        break;

    case "editor":
        System.out.println(
                "Edit access"
        );
        break;

    case "viewer":
        System.out.println(
                "Read-only access"
        );
        break;

    default:
        System.out.println(
                "Unknown role"
        );

}

Supported switch Types

Common Supported Types
switch commonly supports:

byte
short
char
int

Byte
Short
Character
Integer

String

enum types
Unsupported Traditional Types
  • long is not a traditional switch selector type.
  • float is not supported.
  • double is not supported.
  • boolean is not supported.
  • Use if-else for range-based and unsupported-type conditions.

Modern switch Expression

Modern Java supports switch expressions that can directly produce values and use arrow-style case labels.

Modern switch
int day = 2;

String name = switch (day) {

    case 1 -> "Monday";

    case 2 -> "Tuesday";

    case 3 -> "Wednesday";

    case 4 -> "Thursday";

    case 5 -> "Friday";

    case 6 -> "Saturday";

    case 7 -> "Sunday";

    default -> "Invalid day";

};

System.out.println(name);

Arrow Case Labels

Arrow Cases
int day = 7;

switch (day) {

    case 1, 2, 3, 4, 5 ->
        System.out.println("Weekday");

    case 6, 7 ->
        System.out.println("Weekend");

    default ->
        System.out.println("Invalid");

}
Benefits of Arrow Cases
  • No break statement is required.
  • No accidental fall-through occurs.
  • Multiple labels can be separated with commas.
  • The syntax is shorter and often easier to read.

Returning Values from switch

Return a Value
int month = 4;

String season = switch (month) {

    case 12, 1, 2 ->
        "Winter";

    case 3, 4, 5 ->
        "Spring";

    case 6, 7, 8 ->
        "Summer";

    case 9, 10, 11 ->
        "Autumn";

    default ->
        "Invalid month";

};

System.out.println(season);

yield Keyword

When a switch expression case requires multiple statements, a block can use yield to provide the resulting value.

yield Example
int score = 2;

String message = switch (score) {

    case 1 -> "Low";

    case 2 -> {

        System.out.println(
                "Processing medium score"
        );

        yield "Medium";
    }

    case 3 -> "High";

    default -> "Unknown";

};

System.out.println(message);

Traditional vs Modern switch

Comparison
TRADITIONAL SWITCH

Uses case value:
Usually requires break
Can fall through
Primarily statement-oriented


MODERN SWITCH

Uses case value ->
No accidental fall-through
Can return values
Supports comma-separated labels
Uses yield for block results

if-else vs switch

When to Use Each
USE if-else FOR:

Ranges

age >= 18

Complex conditions

age >= 18 && hasId

Different variables

salary > 50000 || creditScore > 750


USE switch FOR:

One expression

Exact known values

Menus

Days

Months

Roles

Commands
Menu Program
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        System.out.println("1. Add");
        System.out.println("2. Edit");
        System.out.println("3. Delete");
        System.out.println("4. Exit");

        System.out.print(
                "Enter your choice: "
        );

        int choice =
                scanner.nextInt();

        switch (choice) {

            case 1 ->
                System.out.println(
                        "Add selected"
                );

            case 2 ->
                System.out.println(
                        "Edit selected"
                );

            case 3 ->
                System.out.println(
                        "Delete selected"
                );

            case 4 ->
                System.out.println(
                        "Exit selected"
                );

            default ->
                System.out.println(
                        "Invalid choice"
                );

        }

    }
}

Simple Calculator

Calculator with switch
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        System.out.print(
                "Enter first number: "
        );

        double first =
                scanner.nextDouble();

        System.out.print(
                "Enter operator (+, -, *, /): "
        );

        char operator =
                scanner.next().charAt(0);

        System.out.print(
                "Enter second number: "
        );

        double second =
                scanner.nextDouble();

        switch (operator) {

            case '+' ->
                System.out.println(
                        first + second
                );

            case '-' ->
                System.out.println(
                        first - second
                );

            case '*' ->
                System.out.println(
                        first * second
                );

            case '/' -> {

                if (second != 0) {

                    System.out.println(
                            first / second
                    );

                } else {

                    System.out.println(
                            "Cannot divide by zero"
                    );

                }

            }

            default ->
                System.out.println(
                        "Invalid operator"
                );

        }

    }
}

Login Validation

Login Program
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner =
                new Scanner(System.in);

        String correctUsername =
                "admin";

        String correctPassword =
                "java123";

        System.out.print(
                "Username: "
        );

        String username =
                scanner.nextLine();

        System.out.print(
                "Password: "
        );

        String password =
                scanner.nextLine();

        if (
            username.equals(correctUsername)
            && password.equals(correctPassword)
        ) {

            System.out.println(
                    "Login successful"
            );

        } else {

            System.out.println(
                    "Invalid credentials"
            );

        }

    }
}

Discount Calculator

Discount Program
double purchaseAmount = 7500;
boolean premiumMember = true;

double discountRate;

if (purchaseAmount >= 10000) {

    discountRate = 0.20;

} else if (
    purchaseAmount >= 5000
    && premiumMember
) {

    discountRate = 0.15;

} else if (purchaseAmount >= 5000) {

    discountRate = 0.10;

} else if (premiumMember) {

    discountRate = 0.05;

} else {

    discountRate = 0.0;

}

double discount =
        purchaseAmount * discountRate;

double finalAmount =
        purchaseAmount - discount;

System.out.printf(
        "Purchase Amount: %.2f%n",
        purchaseAmount
);

System.out.printf(
        "Discount: %.2f%n",
        discount
);

System.out.printf(
        "Final Amount: %.2f%n",
        finalAmount
);

Electricity Bill Example

Electricity Bill
int units = 350;
double bill;

if (units <= 100) {

    bill = units * 2.0;

} else if (units <= 300) {

    bill =
        (100 * 2.0)
        + ((units - 100) * 3.0);

} else {

    bill =
        (100 * 2.0)
        + (200 * 3.0)
        + ((units - 300) * 5.0);

}

System.out.printf(
        "Electricity Bill: %.2f%n",
        bill
);

Leap Year Program

Leap Year Check
int year = 2024;

boolean leapYear =
        year % 400 == 0
        || (
            year % 4 == 0
            && year % 100 != 0
        );

if (leapYear) {

    System.out.println(
            year + " is a leap year."
    );

} else {

    System.out.println(
            year + " is not a leap year."
    );

}
Leap Year Rule
  • A year divisible by 400 is a leap year.
  • Otherwise, a year divisible by 4 but not by 100 is a leap year.
  • All other years are not leap years.
  • Parentheses make the combined condition easier to understand.

Largest of Three Numbers

Find Largest Number
int first = 25;
int second = 80;
int third = 45;

int largest;

if (
    first >= second
    && first >= third
) {

    largest = first;

} else if (
    second >= first
    && second >= third
) {

    largest = second;

} else {

    largest = third;

}

System.out.println(
        "Largest: " + largest
);

Common Conditional Statement Errors

Common Errors
CONDITIONAL ERRORS

├── Using = Instead of ==
├── Using == for String Content
├── Missing Braces
├── Misplaced Semicolon
├── Wrong Condition Order
├── Unreachable else-if Conditions
├── Incorrect Range Boundaries
├── Forgetting Edge Cases
├── Confusing && with ||
├── Forgetting Parentheses
├── Comparing Floating Values Directly
├── Excessive Nesting
├── Complex Ternary Expressions
├── Missing break in Traditional switch
├── Accidental Fall-Through
├── Missing default Case
├── Duplicate Case Labels
├── Unsupported switch Type
├── Forgetting yield in switch Block
├── Accessing null String with equals()
└── Writing Conditions That Can Never Be True
Assignment Instead of Comparison
boolean active = false;

// This assigns true:
if (active = true) {

    System.out.println(
            "Active"
    );

}
Better Boolean Condition
if (active) {

    System.out.println(
            "Active"
    );

}
Misplaced Semicolon
int age = 15;

// Wrong:
if (age >= 18); {

    System.out.println(
            "Adult"
    );

}

The semicolon ends the if statement. The following block executes independently.

Best Practices

  • Use meaningful boolean expressions.
  • Keep conditions easy to read.
  • Use braces consistently.
  • Avoid omitting braces even for one-line blocks.
  • Indent conditional blocks consistently.
  • Use whitespace to separate complex logical expressions.
  • Use parentheses when grouping conditions.
  • Do not rely only on operator precedence when readability suffers.
  • Use == for primitive value comparison.
  • Use equals() for String content comparison.
  • Use equalsIgnoreCase() when case should not matter.
  • Call equals() on a known non-null constant when a variable may be null.
  • Avoid using == to compare String content.
  • Use direct boolean conditions such as if (active).
  • Use !active instead of active == false when appropriate.
  • Check specific conditions before broader overlapping conditions.
  • Order else-if conditions carefully.
  • Use independent if statements when multiple conditions may all be true.
  • Use else-if when only one matching branch should execute.
  • Use nested if statements when separate failure reasons matter.
  • Use logical operators when multiple simple conditions belong to one decision.
  • Avoid excessive nesting.
  • Return early or simplify logic in larger methods when nesting becomes deep.
  • Use && when every requirement must be true.
  • Use || when at least one alternative is sufficient.
  • Use ! to reverse boolean conditions clearly.
  • Understand short-circuit evaluation.
  • Place safety checks before dependent expressions in && conditions.
  • Check null before accessing methods when necessary.
  • Do not compare calculated floating-point values using exact equality when precision matters.
  • Use a suitable tolerance for approximate floating-point comparisons.
  • Use ternary expressions for simple value selection.
  • Avoid nested ternary expressions when readability decreases.
  • Use if-else for complex branching.
  • Use switch when comparing one expression against exact known values.
  • Use if-else for ranges and complex logical conditions.
  • Use default to handle unexpected switch values.
  • Use break in traditional switch statements unless fall-through is intentional.
  • Document intentional fall-through clearly.
  • Prefer modern arrow-style switch syntax when appropriate for the project Java version.
  • Use comma-separated labels for cases with identical behavior.
  • Use switch expressions when a decision directly produces a value.
  • Use yield when a switch expression block must return a value.
  • Validate user input before decision-making.
  • Handle invalid values explicitly.
  • Consider negative values.
  • Consider zero.
  • Consider upper and lower boundaries.
  • Consider null values when working with objects.
  • Test every branch.
  • Test values exactly on condition boundaries.
  • Test values just below boundaries.
  • Test values just above boundaries.
  • Avoid duplicated conditions.
  • Avoid conditions that can never be reached.
  • Avoid conditions that are always true unless intentional.
  • Use boolean variables to name complicated business rules.
  • Extract complex conditions into methods in larger programs.
  • Keep business rules separate from user interface code when applications grow.
  • Do not expose sensitive validation details unnecessarily.
  • Use clear error messages.
  • Prefer readable logic over clever logic.
  • Keep each condition focused on one decision.
  • Use comments to explain why a complex rule exists, not merely what the syntax does.
  • Review condition order whenever business rules change.
  • Use constants for repeated threshold values.
  • Avoid magic numbers in complex decision logic.
  • Keep conditional logic maintainable.
  • Remember that correct boundaries are essential.
  • Understand that one incorrect operator can completely change program behavior.
  • Use automated tests for important decision logic in real applications.

Conditional Statement Checklist

Checklist
CONDITIONAL CHECKLIST

[ ] Condition produces boolean result

[ ] Correct relational operator used

[ ] = and == not confused

[ ] String content uses equals()

[ ] Null values considered

[ ] Braces used consistently

[ ] No accidental semicolon after if

[ ] else-if order is correct

[ ] Specific conditions checked first

[ ] Range boundaries are correct

[ ] Zero is handled

[ ] Negative values are handled

[ ] Upper limits are handled

[ ] Lower limits are handled

[ ] && and || are used correctly

[ ] Parentheses clarify grouping

[ ] Short-circuit behavior understood

[ ] Floating-point equality considered

[ ] Nesting is not excessive

[ ] Ternary remains readable

[ ] switch is used for suitable cases

[ ] Traditional switch has required break

[ ] Fall-through is intentional

[ ] default handles unexpected values

[ ] Modern switch syntax matches Java version

[ ] switch expression returns every required value

[ ] yield used correctly for block results

[ ] Invalid input is handled

[ ] Every branch is tested

[ ] Boundary values are tested

[ ] Logic is readable

[ ] Business rules are maintainable

Common Misconceptions

Avoid These Misconceptions
  • An if condition must evaluate to boolean in Java.
  • Java does not treat every non-zero integer as true.
  • The else block is optional.
  • An if statement can exist without else.
  • Only one branch of an if-else statement executes.
  • Only the first matching branch of an else-if ladder executes.
  • Multiple independent if statements can all execute.
  • The order of else-if conditions matters.
  • A broader condition can make a later specific condition unreachable.
  • Braces are optional only for one controlled statement.
  • Indentation alone does not control Java program structure.
  • A semicolon immediately after if can end the conditional statement.
  • = performs assignment.
  • == performs equality comparison.
  • == does not usually compare String content.
  • equals() compares String content.
  • equalsIgnoreCase() ignores letter case.
  • char values can be compared using ==.
  • Calculated floating-point values may require tolerance-based comparison.
  • && requires both operands to be true.
  • || requires at least one operand to be true.
  • ! reverses a boolean value.
  • && and || use short-circuit evaluation.
  • A ternary operator is an expression and produces a value.
  • Ternary syntax is not always more readable than if-else.
  • Traditional switch statements can fall through.
  • break prevents fall-through in traditional switch statements.
  • The default case handles unmatched values.
  • Modern arrow-style switch cases do not accidentally fall through.
  • Modern switch expressions can return values.
  • yield returns a value from a switch expression block.
  • switch is not ideal for numeric ranges.
  • if-else is often better for complex conditions.
  • The best conditional structure depends on the problem.
  • Shorter code is not automatically better code.
  • Every boundary should be tested.

Practice Exercises

Exercise 1: Positive, Negative, or Zero
  • Read an integer from the user.
  • Print Positive when greater than zero.
  • Print Negative when less than zero.
  • Print Zero when equal to zero.
Exercise 2: Even or Odd
  • Read an integer.
  • Use the remainder operator.
  • Print whether the number is even or odd.
Exercise 3: Voting Eligibility
  • Read the user age.
  • Reject negative ages as invalid.
  • Check whether the user is at least 18.
  • Display an appropriate message.
Exercise 4: Grade Calculator
  • Read marks from 0 to 100.
  • Reject values outside the valid range.
  • Assign grades using an else-if ladder.
  • Test exact grade boundaries.
Exercise 5: Largest of Three
  • Read three numbers.
  • Find the largest number.
  • Handle equal values correctly.
  • Display the result.
Exercise 6: Login System
  • Store a valid username and password.
  • Read credentials from the user.
  • Compare Strings correctly.
  • Display success or failure.
  • Add a separate message for an unknown username.
Exercise 7: Discount Calculator
  • Read the purchase amount.
  • Read whether the customer is a member.
  • Apply different discount rules.
  • Calculate the final amount.
  • Display formatted output.
Exercise 8: Menu Program
  • Display five menu options.
  • Read the user choice.
  • Use switch.
  • Handle invalid choices with default.
Exercise 9: Calculator
  • Read two numbers.
  • Read an operator.
  • Use switch to select the calculation.
  • Handle division by zero.
  • Handle invalid operators.
Exercise 10: Leap Year
  • Read a year.
  • Apply the complete leap-year rule.
  • Use logical operators.
  • Test 2000, 1900, 2024, and 2025.

Common Interview Questions

What is a conditional statement?

A conditional statement controls program execution based on whether a condition evaluates to true or false.

What types of conditional statements are available in Java?

Common decision structures include if, if-else, else-if ladders, nested if statements, the ternary operator, and switch.

What type must an if condition produce?

It must produce a boolean value: true or false.

What is the difference between if and if-else?

An if statement executes a block only when a condition is true. An if-else statement chooses between a true branch and a false branch.

How does an else-if ladder work?

Conditions are checked from top to bottom, and only the first matching branch executes.

What is a nested if statement?

It is an if statement placed inside another conditional block.

What is the difference between multiple if statements and an else-if ladder?

Multiple independent if statements are all checked, while an else-if ladder stops after the first true condition.

What does && mean?

It is the logical AND operator and returns true only when both operands are true.

What does || mean?

It is the logical OR operator and returns true when at least one operand is true.

What does ! mean?

It is the logical NOT operator and reverses a boolean value.

What is short-circuit evaluation?

It means Java may skip evaluating the second operand of && or || when the final result is already known.

Why should Strings not usually be compared with ==?

Because == compares object references, while equals() compares String content.

What is the ternary operator?

It is a conditional expression that selects one of two values based on a boolean condition.

What is switch fall-through?

In a traditional switch statement, execution continues into later cases when break is omitted.

What is the purpose of default in switch?

It handles values that do not match any case label.

What is a switch expression?

A switch expression is a modern form of switch that can directly produce a value.

What does yield do in a switch expression?

It provides the value produced by a multi-statement switch expression block.

When should if-else be preferred over switch?

Use if-else for ranges, complex boolean expressions, and conditions involving different variables.

When should switch be preferred?

Use switch when one expression is compared against a known set of exact values.

Frequently Asked Questions

Can an if statement exist without else?

Yes. The else block is optional.

Can I use an integer directly as an if condition?

No. Java requires a boolean condition.

Why does condition order matter?

An else-if ladder stops at the first true condition, so broader conditions can prevent later specific conditions from being reached.

Should I always use braces?

Using braces consistently is recommended because it improves clarity and reduces maintenance errors.

Can multiple if blocks execute?

Yes, when they are independent if statements and multiple conditions are true.

Can multiple branches of one else-if ladder execute?

No. Only the first matching branch executes.

Should I use == or equals() for Strings?

Use equals() for String content comparison.

Can switch check ranges such as age >= 18?

Traditional switch is primarily designed for matching exact values. if-else is generally better for ranges.

Is break required in modern arrow-style switch cases?

No. Arrow-style cases do not use traditional fall-through behavior.

Can switch return a value?

Yes. Modern switch expressions can directly produce values.

Is the ternary operator faster than if-else?

Performance should not be the main reason to choose between them. Choose the form that makes the code clearer.

What should I learn after conditional statements?

The next lesson covers loops in Java.

Key Takeaways

  • Conditional statements allow programs to make decisions.
  • A Java condition must evaluate to boolean.
  • Java does not treat integers as boolean conditions.
  • The if statement executes code only when a condition is true.
  • The else block executes when the if condition is false.
  • An else block is optional.
  • An else-if ladder checks multiple conditions in order.
  • Only the first true branch of an else-if ladder executes.
  • Multiple independent if statements are all checked.
  • Multiple independent conditions can all execute.
  • Condition order is important.
  • Specific overlapping conditions should usually be checked before broader conditions.
  • Nested if statements place conditions inside other conditional blocks.
  • Nested conditions are useful when different decision stages require different actions.
  • Logical operators can simplify multiple related conditions.
  • && means logical AND.
  • Both operands must be true for && to return true.
  • || means logical OR.
  • At least one operand must be true for || to return true.
  • ! means logical NOT.
  • Logical NOT reverses a boolean value.
  • && and || use short-circuit evaluation.
  • Short-circuit evaluation can prevent unsafe operations.
  • Parentheses improve complex condition readability.
  • == compares primitive values directly.
  • == compares object references for objects.
  • equals() compares String content.
  • equalsIgnoreCase() compares String content without considering letter case.
  • char values can be compared with ==.
  • Calculated floating-point values may require tolerance-based comparison.
  • The ternary operator selects between two values.
  • Ternary syntax uses condition ? trueValue : falseValue.
  • Ternary expressions are useful for simple value selection.
  • Complex nested ternary expressions should usually be avoided.
  • switch compares one expression against case labels.
  • Traditional switch statements use colon-style case labels.
  • break exits a traditional switch statement.
  • Missing break can cause fall-through.
  • The default case handles unmatched values.
  • Multiple traditional case labels can share the same statements.
  • switch can work with String values.
  • switch can work with char values.
  • switch can work with enum values.
  • Traditional switch does not support float or double selectors.
  • Modern switch supports arrow-style case labels.
  • Arrow-style cases do not accidentally fall through.
  • Modern switch can use comma-separated case labels.
  • A switch expression can directly produce a value.
  • yield provides a value from a multi-statement switch expression block.
  • if-else is suitable for ranges.
  • if-else is suitable for complex logical expressions.
  • switch is suitable for exact known values.
  • Braces improve safety and readability.
  • A semicolon immediately after if can cause incorrect behavior.
  • = performs assignment.
  • == performs comparison.
  • Boundary values must be tested.
  • Zero should be considered explicitly when relevant.
  • Negative values should be considered.
  • Invalid input should be handled.
  • Null values should be considered when comparing objects.
  • Every decision branch should be tested.
  • Readable conditions are easier to maintain.
  • Decision-making is a fundamental part of programming.

Summary

Conditional statements allow Java programs to make decisions and execute different code depending on whether conditions are true or false.

The if statement executes code when a condition is true. The if-else statement chooses between two paths, while the else-if ladder handles multiple alternatives.

Multiple independent if statements are all evaluated separately, while an else-if ladder stops after the first matching condition.

Nested if statements support multi-stage decisions. Logical operators such as &&, ||, and ! allow multiple conditions to be combined into larger boolean expressions.

Short-circuit evaluation allows Java to skip unnecessary logical operands when the result is already known. This can improve efficiency and prevent unsafe operations.

Strings should generally be compared using equals() or equalsIgnoreCase() rather than ==. Floating-point calculations may require tolerance-based comparison instead of exact equality.

The ternary operator provides a compact way to choose between two values, but complex decision logic is usually clearer with if-else.

The switch statement is useful when one expression must be compared against several exact values. Traditional switch statements use break to prevent fall-through, while modern switch expressions support arrow labels and can directly produce values.

Choosing the correct conditional structure depends on the problem. Use if-else for ranges and complex conditions, switch for exact known values, and ternary expressions for simple value selection.

Correct condition ordering, clear boundaries, input validation, and thorough testing are essential for reliable decision-making logic.

Lesson 12 Completed
  • You understand what conditional statements are.
  • You understand why programs need decision-making.
  • You understand boolean conditions.
  • You can use the if statement.
  • You understand if syntax.
  • You understand how if works.
  • You can use if with variables.
  • You can use if with user input.
  • You can execute multiple statements inside if.
  • You understand why braces are recommended.
  • You can use if-else.
  • You understand how if-else works.
  • You can check even and odd numbers.
  • You can check voting eligibility.
  • You can classify positive and negative numbers.
  • You can use an else-if ladder.
  • You understand condition order.
  • You can build a grade calculator.
  • You can classify ages.
  • You understand independent if statements.
  • You can compare independent if with else-if.
  • You can use nested if statements.
  • You can build nested login validation.
  • You can build multi-stage eligibility checks.
  • You can compare nested conditions with logical operators.
  • You can use relational operators in conditions.
  • You understand logical AND.
  • You understand logical OR.
  • You understand logical NOT.
  • You can combine multiple conditions.
  • You understand logical operator precedence.
  • You understand short-circuit evaluation.
  • You can compare Strings correctly.
  • You can use equals().
  • You can use equalsIgnoreCase().
  • You can compare char values.
  • You understand floating-point comparison concerns.
  • You can use the ternary operator.
  • You understand ternary syntax.
  • You can write simple ternary expressions.
  • You understand the risks of nested ternary expressions.
  • You can compare if-else with ternary.
  • You understand the switch statement.
  • You understand traditional switch syntax.
  • You understand break.
  • You understand fall-through behavior.
  • You understand the default case.
  • You can combine multiple case labels.
  • You can use switch with char.
  • You can use switch with String.
  • You understand supported switch types.
  • You understand modern switch expressions.
  • You can use arrow case labels.
  • You can return values from switch.
  • You understand the yield keyword.
  • You can compare traditional and modern switch.
  • You know when to use if-else and switch.
  • You can build menu-driven programs.
  • You can build a calculator using switch.
  • You can build login validation.
  • You can build discount calculations.
  • You can build slab-based calculations.
  • You can check leap years.
  • You can find the largest of three values.
  • You can identify common conditional statement errors.
  • You know best practices for Java decision-making.
  • You are ready to learn loops.
Next Lesson →

Loops in Java