if and if-else#
if (condition) {
// runs when condition is true
} else {
// runs otherwise
}
In Java the condition must be a boolean. if (count) or if (x = 5) will not compile - which prevents a classic C bug.
You can vote in 2 year(s).
else-if ladder#
95 -> O (Outstanding) 82 -> A 67 -> B 48 -> C 30 -> F (Fail)
Only the first matching branch runs, so order the conditions carefully (here from highest to lowest).
Nested if and combining conditions#
Eligible for some companies
if में condition हमेशा true या false (boolean) होनी चाहिए। कई conditions जोड़ने के लिए && (और) और || (या) का उपयोग करें। Nested if यानी if के अंदर if - जब पहली शर्त पूरी होने के बाद ही दूसरी जाँचनी हो।
The classic switch statement#
switch compares one value against constant case labels. Each case usually ends with break; without it, execution falls through to the next case:
SAT: lab sessions only
Modern switch expressions (Java 14+)#
The arrow form case X -> ... never falls through, can list several values in one case, and the whole switch can produce a value:
Result: 144.0 Very good
Prefer the arrow form in new code. It is shorter, cannot fall through by accident, and the compiler checks that a switch expression covers every case (that is why it needs default for ints and Strings).
The ternary operator#
For a simple two-way choice that produces a value:
String status = (balance >= 0) ? "OK" : "Overdrawn";
int max = (a > b) ? a : b;
Summary#
ifconditions must be booleans; else-if ladders run only the first true branch.- Classic
switchworks with int, char, String and enum; rememberbreak. - Arrow
switchexpressions (case a, b -> value) never fall through and can return values withyield.