if-else (Decision Making)
The if block runs only when the condition is true. If it's false, the else block runs instead.
You can chain multiple conditions with else if — like checking one gate after another.
int marks = 85;
if (marks >= 90) {
System.out.println("A grade");
} else if (marks >= 60) {
System.out.println("B grade");
} else {
System.out.println("Keep trying!");
}- if runs when the condition is true
- else runs when it's false
- else if lets you check multiple conditions
Writing an if-else inside another if-else is called "nesting" — for when you need to check two or more independent conditions, one inside another. Each nested level makes its own true/false decision, which may depend on the outer condition.
Too much nesting (beyond 3-4 levels) makes code hard to read — this is sometimes called "arrow code" or the "pyramid of doom" (the indentation forms a pyramid shape). To avoid this, use the "early return" pattern — return/continue early when a condition doesn't match, keeping the main logic flat.
if (age >= 18) {
if (hasID) {
System.out.println("Entry allowed");
} else {
System.out.println("ID chahiye");
}
} else {
System.out.println("Underage");
}A simple if-else that's just assigning one value can be written in a single line using the ternary operator — the code gets shorter and sometimes more readable. But chaining ternaries (nested ternary) — like a ? b : c ? d : e — gets very confusing and should normally be avoided, even if it looks short.
Rule of thumb: use ternary when you're just deciding between "this value or that value". If you need to take an action (print, method call, multiple statements), a normal if-else is better.
String result = (marks >= 40) ? "Pass" : "Fail";
// Avoid: nested ternary jaise ye padhna mushkil hai:
// String grade = (m>=90) ? "A" : (m>=75) ? "B" : (m>=60) ? "C" : "F";The most common mistake: writing = instead of == (assignment vs comparison). The good news is that code like if(x = 5) won't even compile in Java (because = returns an int, not a boolean) — much better than C/C++'s silent bug, where such code runs quietly.
Second mistake: "dangling else" confusion — else always attaches to the nearest (most recent) if, no matter what the indentation suggests. So using braces {} is always safe even for a single statement — indentation means nothing to the compiler, it's only for humans to read.
Third mistake: comparing Strings with == (if (name == "Aarav")) — this compares references, not content. Always use .equals() for Strings.