☕ Java Conditional Statements — Complete Deep Revision Guide

📖 Conditional Statements Kya Hain?

Normal program:        Conditional program:
Line 1                 Line 1
Line 2                 if(condition) {
Line 3                     Line 2  ← sirf tab chalega
Line 4                 } else {
                           Line 3  ← warna yeh chalega
                       }

Program ka flow control karna — kab kya execute hoga yeh decide karna.

🔵 Topic 1: Simple if Statement

Deep Explanation:

if (condition) {
    // sirf tab chalega jab condition TRUE ho
}

Flow:

condition TRUE  → block execute hoga
condition FALSE → block skip hoga, aage badhega
📁 If1.java
public class If1 {
    public static void main(String[] args) {

        int age = 20;

        // Simple if - condition true toh block chalega
        if (age >= 18) {
            System.out.println("You can vote!");
            System.out.println("Age: " + age);
        }

        System.out.println("Program continues..."); // hamesha chalega

        int marks = 30;
        if (marks >= 35) {
            System.out.println("PASS"); // yeh nahi chalega
        }

        System.out.println("Check complete"); // yeh chalega
    }
}
▶ OUTPUT
You can vote!
Age: 20
Program continues...
Check complete
💡 Short Explain: age=20 >= 18 toh if block chala. marks=30 < 35 toh if block skip hua. Program dono case mein aage badha.
📁 If2.java
public class If2 {
    public static void main(String[] args) {

        int temperature = 38;

        if (temperature > 37) {
            System.out.println("You have fever!");
        }

        int balance  = 5000;
        int withdraw = 3000;

        if (balance >= withdraw) {
            balance = balance - withdraw;
            System.out.println("Withdrawal successful!");
            System.out.println("Remaining balance: Rs." + balance);
        }

        // Single line if (no curly braces - sirf ek statement)
        int num = -5;
        if (num < 0) System.out.println(num + " is negative");
    }
}
▶ OUTPUT
You have fever!
Withdrawal successful!
Remaining balance: Rs.2000
-5 is negative
💡 Single statement ke liye {} optional hai. But multiple statements ke liye {} zaroori hai.

🟢 Topic 2: if-else Statement

Deep Explanation:

if (condition) {
    // TRUE hone par
} else {
    // FALSE hone par
}

Flow:

condition TRUE  → if block chalega, else skip
condition FALSE → if skip, else block chalega
Dono mein se SIRF EK chalega hamesha!
📁 IfElse1.java
public class IfElse1 {
    public static void main(String[] args) {

        int marks = 72;

        if (marks >= 35) {
            System.out.println("Result: PASS ✓");
            System.out.println("Marks: " + marks);
        } else {
            System.out.println("Result: FAIL ✗");
            System.out.println("Need 35, got: " + marks);
        }

        // Even or Odd
        int num = 17;
        if (num % 2 == 0) {
            System.out.println(num + " is Even");
        } else {
            System.out.println(num + " is Odd");
        }
    }
}
▶ OUTPUT
Result: PASS ✓
Marks: 72
17 is Odd
📁 IfElse2.java
public class IfElse2 {
    public static void main(String[] args) {

        // ATM withdrawal
        double balance        = 5000;
        double withdrawAmount = 8000;

        if (balance >= withdrawAmount) {
            balance -= withdrawAmount;
            System.out.println("Withdrawal: Rs." + withdrawAmount);
            System.out.println("Remaining:  Rs." + balance);
        } else {
            System.out.println("Insufficient balance!");
            System.out.println("Available:  Rs." + balance);
            System.out.println("Requested:  Rs." + withdrawAmount);
        }

        // Login check
        String correctPass = "java123";
        String userPass    = "java123";

        if (correctPass.equals(userPass)) {
            System.out.println("\nLogin Successful!");
        } else {
            System.out.println("\nWrong Password!");
        }
    }
}
▶ OUTPUT
Insufficient balance!
Available: Rs.5000.0
Requested: Rs.8000.0

Login Successful!
💡 String comparison mein == mat use karo — .equals() use karo! == address compare karta hai, .equals() value compare karta hai.
📁 IfElse3.java
public class IfElse3 {
    public static void main(String[] args) {

        // Max of two numbers
        int a = 45, b = 67;
        int max;

        if (a > b) {
            max = a;
        } else {
            max = b;
        }
        System.out.println("Max of " + a + " and " + b + " = " + max);

        // Positive or Negative
        int num = -23;
        if (num >= 0) {
            System.out.println(num + " is Positive or Zero");
        } else {
            System.out.println(num + " is Negative");
        }

        // Discount logic
        int    price      = 1500;
        double finalPrice;
        if (price > 1000) {
            finalPrice = price * 0.90; // 10% discount
            System.out.println("10% discount applied!");
        } else {
            finalPrice = price;
            System.out.println("No discount");
        }
        System.out.println("Final Price: Rs." + finalPrice);
    }
}
▶ OUTPUT
Max of 45 and 67 = 67
-23 is Negative
10% discount applied!
Final Price: Rs.1350.0

🟡 Topic 3: if-else-if Ladder

Deep Explanation:

if (condition1) {
    // condition1 true
} else if (condition2) {
    // condition2 true
} else if (condition3) {
    // condition3 true
} else {
    // sab false
}

Important: Conditions upar se neeche check hoti hain. Pehli true condition ka block chalega, baaki skip!

marks = 85
if(marks >= 90)      → false, skip
else if(marks >= 75) → TRUE! → "A" print, BAAKI SKIP
else if(marks >= 60) → check hi nahi hoga
else                  → check hi nahi hoga
📁 IfElseIf1.java
public class IfElseIf1 {
    public static void main(String[] args) {

        int marks = 85;

        if (marks >= 90) {
            System.out.println("Grade: A+");
        } else if (marks >= 75) {
            System.out.println("Grade: A");   // yeh chalega
        } else if (marks >= 60) {
            System.out.println("Grade: B");
        } else if (marks >= 35) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: F - FAIL");
        }

        System.out.println("Marks: " + marks);
    }
}
▶ OUTPUT
Grade: A
Marks: 85
📁 IfElseIf2.java
public class IfElseIf2 {
    public static void main(String[] args) {

        // BMI Calculator
        double bmi = 27.5;

        System.out.println("BMI: " + bmi);

        if (bmi < 18.5) {
            System.out.println("Category: Underweight");
        } else if (bmi < 25.0) {
            System.out.println("Category: Normal weight");
        } else if (bmi < 30.0) {
            System.out.println("Category: Overweight"); // yeh chalega
        } else {
            System.out.println("Category: Obese");
        }

        // Speed check
        int speed = 95;
        if (speed <= 40) {
            System.out.println("\nSpeed: Too Slow");
        } else if (speed <= 60) {
            System.out.println("\nSpeed: Normal");
        } else if (speed <= 80) {
            System.out.println("\nSpeed: Fast");
        } else {
            System.out.println("\nSpeed: Overspeeding! Fine!");
        }
    }
}
▶ OUTPUT
BMI: 27.5
Category: Overweight

Speed: Overspeeding! Fine!
📁 IfElseIf3.java
public class IfElseIf3 {
    public static void main(String[] args) {

        // Electricity bill calculator
        int    units = 250;
        double bill;

        if (units <= 50) {
            bill = units * 1.50;
        } else if (units <= 150) {
            bill = 50 * 1.50 + (units - 50) * 2.50;
        } else if (units <= 300) {
            // 50*1.5 + 100*2.5 + remaining*4
            bill = 50 * 1.50 + 100 * 2.50 + (units - 150) * 4.00;
        } else {
            bill = 50 * 1.50 + 100 * 2.50 + 150 * 4.00 + (units - 300) * 5.00;
        }

        System.out.println("Units used: " + units);
        System.out.println("Total Bill: Rs." + bill);

        // Season check
        int month = 7;
        if (month >= 3 && month <= 5) {
            System.out.println("\nMonth " + month + ": Summer");
        } else if (month >= 6 && month <= 9) {
            System.out.println("\nMonth " + month + ": Monsoon");
        } else if (month >= 10 && month <= 11) {
            System.out.println("\nMonth " + month + ": Autumn");
        } else {
            System.out.println("\nMonth " + month + ": Winter");
        }
    }
}
▶ OUTPUT
Units used: 250
Total Bill: Rs.725.0

Month 7: Monsoon
📁 IfElseIf4.java
public class IfElseIf4 {
    public static void main(String[] args) {

        // Nested if - if ke andar if
        int     age        = 25;
        boolean hasLicense = true;
        boolean hasCar     = false;

        if (age >= 18) {
            System.out.println("Age: OK");
            if (hasLicense) {
                System.out.println("License: OK");
                if (hasCar) {
                    System.out.println("Can drive own car!");
                } else {
                    System.out.println("Can drive rented car!");
                }
            } else {
                System.out.println("Get license first!");
            }
        } else {
            System.out.println("Too young to drive!");
        }
    }
}
▶ OUTPUT
Age: OK
License: OK
Can drive rented car!
💡 Nested if mein ek if ke andar doosra if hota hai. Har level ki apni condition hoti hai — andar ka if sirf tab check hoga jab bahar wala true ho.

🔴 Topic 4: switch Statement

Deep Explanation:

switch (variable) {
    case value1:
        // code
        break;      ← ZAROORI warna fall-through!
    case value2:
        // code
        break;
    default:        ← optional, koi match nahi toh
        // code
}

Switch Rules — Exam Mein Aata Hai:

✅ Allowed types: byte, short, int, char, String, enum
❌ NOT allowed:   long, float, double, boolean

✅ Case values: constant ya final variable
❌ NOT allowed: normal variable as case value

✅ break: optional but recommended
❌ Bina break: fall-through hoga (saare neeche wale case chalenge!)

✅ default: optional
✅ Ek se zyada case same code share kar sakte hain
📁 Switch1.java
public class Switch1 {
    public static void main(String[] args) {

        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"); // yeh chalega
                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!");
        }
    }
}
▶ OUTPUT
Wednesday
💡 day=3 toh case 3 match hua, "Wednesday" print hua, break se switch se bahar nikle. Baaki cases skip hue.
📁 Switch2.java — Fall-through demonstration
public class Switch2 {
    public static void main(String[] args) {

        int num = 2;

        System.out.println("--- With break ---");
        switch (num) {
            case 1: System.out.println("One");   break;
            case 2: System.out.println("Two");   break; // sirf yeh
            case 3: System.out.println("Three"); break;
        }

        System.out.println("\n--- WITHOUT break (fall-through!) ---");
        switch (num) {
            case 1: System.out.println("One");
            case 2: System.out.println("Two");           // yahan se shuru
            case 3: System.out.println("Three");         // yeh bhi chala!
            case 4: System.out.println("Four");          // yeh bhi!
            default: System.out.println("Default also!"); // yeh bhi!
        }
    }
}
▶ OUTPUT
--- With break ---
Two

--- WITHOUT break (fall-through!) ---
Two
Three
Four
Default also!
💡 Bina break ke matched case ke baad ke saare cases execute hote hain — isko fall-through kehte hain. Yeh bug create karta hai usually, isliye break lagao!
📁 Switch3.java — Multiple cases same code
public class Switch3 {
    public static void main(String[] args) {

        // Weekend check - intentional fall-through
        int day = 6;

        switch (day) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("Weekday - Office day!");
                break;
            case 6:
            case 7:
                System.out.println("Weekend - Holiday!"); // yeh chalega
                break;
            default:
                System.out.println("Invalid day!");
        }

        // Vowel check using char
        char ch = 'e';
        switch (ch) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                System.out.println(ch + " is a Vowel");
                break;
            default:
                System.out.println(ch + " is a Consonant");
        }
    }
}
▶ OUTPUT
Weekend - Holiday!
e is a Vowel
💡 Yahan fall-through intentional hai — multiple cases ko same code share karna hai. case 6: case 7: dono "Weekend" print karenge.
📁 Switch4.java — String switch
public class Switch4 {
    public static void main(String[] args) {

        String color = "RED";

        switch (color) {           // String switch
            case "RED":
                System.out.println("Stop!");
                break;
            case "YELLOW":
                System.out.println("Get Ready!");
                break;
            case "GREEN":
                System.out.println("Go!");
                break;
            default:
                System.out.println("Invalid color!");
        }

        // Case-sensitive hai String switch!
        String lang = "java"; // lowercase

        switch (lang) {
            case "Java":  // uppercase J
                System.out.println("Matched Java");
                break;
            case "java":  // lowercase j
                System.out.println("Matched java"); // yeh chalega
                break;
            default:
                System.out.println("No match");
        }
    }
}
▶ OUTPUT
Stop!
Matched java
💡 String switch case-sensitive hai! "Java" aur "java" alag cases hain. Java 7 se pehle String switch allowed nahi tha.
📁 Switch5.java — Switch rules: final variable & constant
public class Switch5 {
    public static void main(String[] args) {

        // Rule 1: Case value constant honi chahiye
        final int ONE = 1;    // ✅ final variable - allowed
        final int TWO = 2;    // ✅ final variable - allowed
        // int three = 3;     // ❌ normal variable - NOT allowed as case

        int x = 2;
        switch (x) {
            case ONE:          // ✅ final variable allowed
                System.out.println("One");
                break;
            case TWO:          // ✅ final variable allowed
                System.out.println("Two");  // yeh chalega
                break;
            case 3:            // ✅ literal constant - always allowed
                System.out.println("Three");
                break;
            default:
                System.out.println("Other");
        }

        // Rule 2: long, float, double NOT allowed
        // long l = 5L;
        // switch(l) { }  // ❌ Compile Error!

        // Rule 3: Default anywhere rakh sakte hain
        int y = 10;
        switch (y) {
            default:              // default pehle bhi rakh sakte hain!
                System.out.println("Default case");
                break;
            case 10:
                System.out.println("Ten");  // yeh chalega (case match)
                break;
        }
    }
}
▶ OUTPUT
Two
Ten
💡 final variable case mein allowed hai kyunki compiler uski value fix jaanta hai (Constant Folding). Normal variable allowed nahi — runtime tak value pata nahi hoti.
📁 Switch6.java — Calculator + Month name
public class Switch6 {
    public static void main(String[] args) {

        // Simple Calculator using switch
        int  a        = 20, b = 5;
        char operator = '*';

        switch (operator) {
            case '+':
                System.out.println(a + " + " + b + " = " + (a + b));
                break;
            case '-':
                System.out.println(a + " - " + b + " = " + (a - b));
                break;
            case '*':
                System.out.println(a + " * " + b + " = " + (a * b)); // yeh
                break;
            case '/':
                if (b != 0)
                    System.out.println(a + " / " + b + " = " + (a / b));
                else
                    System.out.println("Cannot divide by zero!");
                break;
            case '%':
                System.out.println(a + " % " + b + " = " + (a % b));
                break;
            default:
                System.out.println("Invalid operator!");
        }

        // Month name
        int    month = 4;
        String monthName;
        switch (month) {
            case  1:  monthName = "January";   break;
            case  2:  monthName = "February";  break;
            case  3:  monthName = "March";     break;
            case  4:  monthName = "April";     break;
            case  5:  monthName = "May";       break;
            case  6:  monthName = "June";      break;
            case  7:  monthName = "July";      break;
            case  8:  monthName = "August";    break;
            case  9:  monthName = "September"; break;
            case 10:  monthName = "October";   break;
            case 11:  monthName = "November";  break;
            case 12:  monthName = "December";  break;
            default:  monthName = "Invalid";
        }
        System.out.println("Month " + month + " = " + monthName);
    }
}
▶ OUTPUT
20 * 5 = 100
Month 4 = April
📁 Switch7.java — String switch + Menu System
public class Switch7 {
    public static void main(String[] args) {

        String userChoice = "pizza";

        // toLowerCase() use karo - case insensitive banana ke liye
        switch (userChoice.toLowerCase()) {
            case "pizza":
                System.out.println("Pizza ordered - Rs.299");
                System.out.println("Delivery: 30 min");
                break;
            case "burger":
                System.out.println("Burger ordered - Rs.149");
                System.out.println("Delivery: 20 min");
                break;
            case "pasta":
                System.out.println("Pasta ordered - Rs.199");
                System.out.println("Delivery: 25 min");
                break;
            case "exit":
                System.out.println("Goodbye!");
                break;
            default:
                System.out.println("Item not available!");
        }

        // Exam: default without break - kya hoga?
        int val = 99;
        switch (val) {
            case 1:
                System.out.println("One");
                break;
            default:
                System.out.println("Default"); // yeh chalega
                // break nahi hai - but koi case neeche nahi toh OK
            case 2:
                System.out.println("Two");
                // no break - fall through to... nothing (switch ends)
        }
    }
}
▶ OUTPUT
Pizza ordered - Rs.299
Delivery: 30 min
Default
💡 .toLowerCase() use karke case-insensitive comparison kar sakte hain String switch mein. "PIZZA", "Pizza", "pizza" sab match ho jaayenge.

📋 Complete Revision Summary

StatementKab Use KareinKey Point
if Sirf ek condition check True → block chale, False → skip
if-else 2 paths — TRUE ya FALSE Hamesha EK hi path chalega
if-else-if Multiple conditions chain Upar se neeche check, pehli match pe stop. Nested if bhi possible.
switch Ek variable kai values se compare break zaroori warna fall-through. Types: byte short int char String enum. long float double NAHI allowed.

⭐ Switch Rules — Exam Sheet

✅ Allowed: byte, short, int, char, String, enum
❌ Banned: long, float, double, boolean

✅ Case value: literal (1, 2, 'a') ya final variable
❌ Case value: normal variable nahi chalega

✅ break: switch se bahar nikalo
❌ No break: fall-through — neeche ke sab cases chalenge

✅ default: optional, koi match nahi toh chalta hai
✅ default: anywhere rakh sakte hain (top, middle, end)

✅ Multiple cases same code share kar sakte hain:
   case 1:
   case 2:
       System.out.println("same"); // 1 ya 2 dono ke liye

✅ String switch: Java 7 se, case-sensitive!
✅ Constant Folding: final variable ki value compiler replace karta hai

⚠️ Common Mistakes

MistakeWrong ❌Right ✅
Assignment vs Comparisonif(x = 5)if(x == 5)
String comparisonif(s == "hi")if(s.equals("hi"))
Switch with longswitch(longVar)Use int instead
Variable in casecase x: (normal var)case 5: ya final var
Forgetting breakFall-through bugAdd break after each case
Case sensitivitycase "Java": for "java".toLowerCase() first
🏆 Golden Rule File name = Class name exactly! Jaise class Switch1 hai toh file Switch1.java hogi!