If-Else Statements
Overview
Programs need to make decisions. If-Else statements are how we tell the computer: 'If this specific condition is true, do this. Otherwise, do that.'
Imagine a bouncer at a club. The bouncer checks your ID. If you are 18 or older, they let you in. Else, they turn you away. This is called 'Control Flow', because it controls the direction your code flows in.
1. The Basic 'If'
The simplest form. It checks a condition (must result in true or false). If true, it runs the block of code inside the curly braces `{}`.
2. 'Else' and 'Else If'
You can chain conditions together. 'Else If' lets you check a second condition if the first one failed. 'Else' is the final catch-all if everything else failed.
3. Comparing Strings (Warning!)
When comparing text (Strings), NEVER use `==`. You must use `.equals()`. This is a very common beginner mistake.
Syntax
Java checks conditions top-to-bottom. The first one that is true gets executed, and the rest are ignored.
int score = 85;
if (score >= 90) {
System.out.println("You got an A!");
} else if (score >= 80) {
System.out.println("You got a B!");
} else {
System.out.println("You need to study more.");
}Always use .equals() for text comparison.
String password = "secret123";
// ❌ BAD: password == "secret123"
// ✅ GOOD:
if (password.equals("secret123")) {
System.out.println("Login successful!");
} else {
System.out.println("Wrong password.");
}Common Pitfalls
- Forgetting curly braces `{}`. If you don't use them, only the very next line of code is considered part of the 'if' statement, which causes confusing bugs.
Interview Tips
- Always mention `.equals()` when comparing Strings. Explain that `==` compares the physical memory location, while `.equals()` compares the actual text.
Real-World Example
If-else is heavily used in apps to show different screens based on user status.
public class AuthCheck {
public static void main(String[] args) {
boolean isLoggedIn = true;
boolean isAdmin = false;
if (!isLoggedIn) {
System.out.println("Redirecting to Login Page...");
} else if (isAdmin) {
System.out.println("Showing Admin Dashboard...");
} else {
System.out.println("Showing Regular User Homepage...");
}
}
}