Java Conditional (Java If ... Else)

Conditions and if statements let you control the flow of your program - deciding which code runs, and which code is skipped.

Basically:

  • Purpose: Control the flow of a program by deciding which code runs based on a condition.

  • Real‑life analogy:
    If it rains → take an umbrella; else → do nothing.

  • Key point: Conditions must evaluate to true or false.

Java Conditional Keywords

Keyword

Purpose

if

Executes a block if the condition is true.

else

Executes a block if the same condition is false.

else if

Tests a new condition if the previous if or else if was false.

switch

Tests one variable against multiple possible values

(alternative to many else if).

Proper Syntax and Structure

Basic If:

if (condition) {

// code runs if condition is true

}

If… else:

switch if (condition) {

    // code if true

} else {

// code if false

}

   

If…else if…else

if (condition1) {

// code if condition1 is true

} else if (condition2) {

// code if condition2 is true

} else {

// code if none are true

}

Comparison Operators in Conditions

Operators

Meaning

<

Less Than

<=

Less Than or Equal to

>

Greater Than

>=

Greater Than or Equal to

==

Equal to

!=

No Equal to

Example Statements:

  1. Basic if

if (20 > 18) { System.out.println( “20 is greater than 18” ) }
  1. Using Variables

    int x = 20;
    int y = 18;
    if (x > y) {
        System.out.println("x is greater than y");
    }
  2. If Else

    int time = 20;
    if (time < 18) {
        System.out.println("Good day.");
    } else {
        System.out.println("Good evening.");
    }
  3. If Else if Else

    int age = 15;
    if (age < 13) {
        System.out.println("You are a child");
    } else if (age < 20) {
        System.out.println("You are a teenager");
    } else {
        System.out.println("You are an adult");
    }
  4. With Boolean Variables

    boolean isLightOn = true;
    if (isLightOn) {
        System.out.println("The light is on.");
    }

Java Short Hand If...Else (Ternary Operator)

Structure:

variable = (condition) ? expressionTrue : expressionFalse;

Example:

int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);

——————————————————————————————————————————

🔍 Quick Summary

• if → runs code if condition is true.

• else → runs code if condition is false.

• else if → checks additional conditions.

• Ternary operator → short form for simple if…else.

• Always ensure conditions return a Boolean.

8⃣ Common Mistakes to Avoid

  • Using = instead of == in comparisons.

  • Forgetting curly braces {} for multi‑line blocks.

  • Writing If or IF instead of lowercase if.