๐ฆ 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
- Start Simple โ Use
iffor basic checks - Two Paths? โ Use
if-else - Many Options? โ Consider
switch - Need a Value Back? โ Use enhanced
switchwith arrows - 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!