Conditional Statements

Loading concept...

๐Ÿšฆ Control Flow: The Traffic Lights of Your Code

Imagine youโ€™re driving a car. You come to a crossroad. Do you go left, right, or straight? The traffic light tells you what to do. Conditional statements in Java work exactly like traffic lights โ€” they help your program decide which path to take!


๐ŸŒŸ The Big Picture

Every day, you make choices:

  • If itโ€™s raining, take an umbrella
  • If youโ€™re hungry, eat lunch; otherwise, keep playing
  • If itโ€™s Monday, go to school; if Saturday, play games

Java does the same thing! It looks at a condition (like checking the weather) and picks what to do next.


๐Ÿ”น 1. The Simple if Statement

What is it?

The if statement is like asking a yes/no question. If the answer is YES, do something. If NO, skip it.

Real Life Example

โ€œIf you finished your homework, you can play games.โ€

Java Code

int homework = 100; // homework done!

if (homework == 100) {
    System.out.println("You can play games! ๐ŸŽฎ");
}

How it Works

graph TD A[Start] --> B{homework == 100?} B -->|Yes| C[Play games! ๐ŸŽฎ] B -->|No| D[Nothing happens] C --> E[Continue] D --> E

Key Point: If the condition is true, the code inside { } runs. If false, Java skips it entirely.


๐Ÿ”น 2. The if-else Statement

What is it?

Sometimes you need a Plan B! The if-else says: โ€œIf this is true, do A. Otherwise, do B.โ€

Real Life Example

โ€œIf itโ€™s sunny, go to the park. Otherwise, stay home and read.โ€

Java Code

String weather = "rainy";

if (weather.equals("sunny")) {
    System.out.println("Go to the park! โ˜€๏ธ");
} else {
    System.out.println("Stay home and read ๐Ÿ“š");
}

How it Works

graph TD A[Start] --> B{Is it sunny?} B -->|Yes| C[Go to park โ˜€๏ธ] B -->|No| D[Stay home ๐Ÿ“š] C --> E[Continue] D --> E

Remember: One condition, two possible paths. Always one will run!


๐Ÿ”น 3. The if-else-if Ladder

What is it?

What if you have MORE than two choices? Like a restaurant menu! You check each option until you find a match.

Real Life Example

โ€œWhat grade did you get?โ€

  • If A โ†’ Excellent!
  • If B โ†’ Good job!
  • If C โ†’ Keep trying!
  • Otherwise โ†’ Study more!

Java Code

char grade = 'B';

if (grade == 'A') {
    System.out.println("Excellent! ๐ŸŒŸ");
} else if (grade == 'B') {
    System.out.println("Good job! ๐Ÿ‘");
} else if (grade == 'C') {
    System.out.println("Keep trying! ๐Ÿ’ช");
} else {
    System.out.println("Study more! ๐Ÿ“–");
}

How it Works

graph TD A[Check Grade] --> B{A?} B -->|Yes| C[Excellent ๐ŸŒŸ] B -->|No| D{B?} D -->|Yes| E[Good job ๐Ÿ‘] D -->|No| F{C?} F -->|Yes| G[Keep trying ๐Ÿ’ช] F -->|No| H[Study more ๐Ÿ“–]

Pro Tip: Java checks from TOP to BOTTOM. First match wins!


๐Ÿ”น 4. The switch Statement

What is it?

Imagine a TV remote. You press button 1, channel 1 appears. Press 2, channel 2 plays. The switch statement works like this โ€” jump directly to the matching case!

Why Use Switch?

When you have MANY options to check against ONE variable, switch is cleaner and faster than a long if-else-if ladder.

Java Code

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;
    default:
        System.out.println("Another day");
}

Output

Wednesday ๐Ÿ“…

The break is Important!

Without break, Java keeps running into the next case (called โ€œfall-throughโ€):

int num = 1;

switch (num) {
    case 1:
        System.out.println("One");
        // No break here!
    case 2:
        System.out.println("Two");
        break;
}
// Prints: One AND Two!
graph TD A[switch day] --> B{case 1?} B -->|Yes| C[Monday] B -->|No| D{case 2?} D -->|Yes| E[Tuesday] D -->|No| F{case 3?} F -->|Yes| G[Wednesday] F -->|No| H[default]

๐Ÿ”น 5. Enhanced Switch Expressions (Java 14+)

What is it?

The new and improved switch! Itโ€™s shorter, cleaner, and can return a value directly. Think of it as a modern TV remote with touchscreen instead of buttons.

Old vs New

Old Way:

String result;
switch (day) {
    case 1:
        result = "Monday";
        break;
    case 2:
        result = "Tuesday";
        break;
    default:
        result = "Unknown";
}

New Way (Arrow Syntax):

String result = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    default -> "Unknown";
};

Features of Enhanced Switch

1. Arrow Syntax (->) โ€” No break needed!

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 -> "Fall ๐Ÿ‚";
    default -> "Invalid";
};

2. Multiple Labels โ€” Group cases together with commas!

3. Yield Keyword โ€” For complex logic inside a case:

String message = switch (score) {
    case 100 -> "Perfect!";
    case 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 -> {
        System.out.println("Almost there!");
        yield "Excellent";
    }
    default -> "Good try";
};

Remember: Use yield when you have multiple statements in a block and need to return a value.


๐Ÿ”น 6. Pattern Matching (Java 16+)

What is it?

Pattern matching is like having X-ray vision! Instead of just checking a value, Java can check the TYPE of something and give you a new variable automatically.

The Problem Before

Object obj = "Hello World";

if (obj instanceof String) {
    String s = (String) obj; // Manual cast ๐Ÿ˜ซ
    System.out.println(s.length());
}

Pattern Matching Solution

Object obj = "Hello World";

if (obj instanceof String s) {
    // 's' is automatically a String! โœจ
    System.out.println(s.length());
}

How it Works

graph TD A[Object obj] --> B{instanceof String?} B -->|Yes| C[Create String s] C --> D[Use s directly] B -->|No| E[Skip this block]

Pattern Matching in Switch (Java 21+)

Object data = 42;

String result = switch (data) {
    case Integer i -> "Number: " + i;
    case String s -> "Text: " + s;
    case null -> "Nothing!";
    default -> "Unknown type";
};

Guarded Patterns

You can add extra conditions with when:

Object value = 25;

String result = switch (value) {
    case Integer i when i > 0 -> "Positive";
    case Integer i when i < 0 -> "Negative";
    case Integer i -> "Zero";
    default -> "Not a number";
};

๐ŸŽฏ Quick Comparison Table

Feature Use When
if One simple condition
if-else Two choices (true/false)
if-else-if Multiple conditions, different types
switch Many cases for ONE variable
Enhanced switch Return values, cleaner syntax
Pattern Matching Check type + extract value

๐Ÿ’ก Golden Rules

  1. Start Simple โ€” Use if for basic checks
  2. Two Paths? โ€” Use if-else
  3. Many Options? โ€” Consider switch
  4. Need a Value Back? โ€” Use enhanced switch with arrows
  5. Checking Types? โ€” Pattern matching is your friend!

๐Ÿš€ Youโ€™re Ready!

You now understand how Java makes decisions. Just like traffic lights guide cars, these statements guide your code. Practice with different scenarios, and soon youโ€™ll be directing traffic like a pro! ๐ŸŽ‰

Next step: Try writing your own day-of-week program using all these concepts!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.