Part 03 / Topic 1 of 8
if/else and nested conditionals
An if runs a block only when its condition is true. else runs when it is false. Chain several conditions, checked in order, with else if. Put an if inside another if (nested) when the second question only makes sense once the first answer is known.
int age = 24;
int monthlyIncome = 32000;
boolean hasExistingLoan = false;
if (age >= 21) {
if (monthlyIncome >= 25000) {
if (!hasExistingLoan) {
System.out.println("Eligible for the full loan amount.");
} else {
System.out.println("Eligible, but for a smaller amount (existing loan).");
}
} else {
System.out.println("Not eligible: income below Rs 25000.");
}
} else {
System.out.println("Not eligible: age below 21.");
}
Output:
Eligible for the full loan amount.
Nesting only makes sense when a question is conditional on a previous answer — "is the income high enough" is meaningless to ask if the age check already failed. If every question stands on its own, an else-if ladder is clearer than nesting:
int units = 180;
double bill;
if (units <= 100) {
bill = units * 3.5;
} else if (units <= 200) {
bill = 100 * 3.5 + (units - 100) * 5.0;
} else if (units <= 300) {
bill = 100 * 3.5 + 100 * 5.0 + (units - 200) * 6.5;
} else {
bill = 100 * 3.5 + 100 * 5.0 + 100 * 6.5 + (units - 300) * 8.0;
}
System.out.println("Units: " + units + " -> Bill: Rs " + bill);
Output:
Units: 180 -> Bill: Rs 750.0
Each branch is checked in order, and the first one that matches wins — the later ones never even get checked. That is why the slabs above each subtract the units already billed at the earlier slab's rate.
The ternary operator ?:
For a short "pick one of two values" decision, the ternary operator fits on one line: condition ? valueIfTrue : valueIfFalse.
int pinAttemptsLeft = 1;
String warning = pinAttemptsLeft == 1 ? "Last attempt!" : "Try again.";
System.out.println(warning);
int a = 7, b = 12;
int larger = a > b ? a : b;
System.out.println("Larger of " + a + " and " + b + " is " + larger);
Output:
Last attempt!
Larger of 7 and 12 is 12
Use ?: only to pick a value. The moment you need more than one statement per branch, go back to a full if/else — a ternary stuffed with side effects is hard to read.
Full program: examples/01_if_else.java.
Done here? The practice set for Part 3 — including the solutions — is on the part page.