4 min readβ’june 18, 2024
Avanish Gupta
Avanish Gupta
some code run before
if (condition1) {
code that runs if condition1 is true
} else if (condition2) {
code that runs if condition2 is true
while condition1 is false
} else if (condition3) {
code that runs if condition3 is true
while condition1 and condition2 are false
} .
.
.
else {
code that runs if none of the
conditions above are true
}
Example: Divisibility Counter
public static int largestDivisorLessThanTen(int number) {
if (number % 10 == 0) {
return 10;
} else if (number % 9 == 0) {
return 9;
} else if (number % 8 == 0) {
return 8;
} else if (number % 7 == 0) {
return 7;
} else if (number % 6 == 0) {
return 6;
} else if (number % 5 == 0) {
return 5;
} else if (number % 4 == 0) {
return 4;
} else if (number % 3 == 0) {
return 3;
} else if (number % 2 == 0) {
return 2;
} else {
return 1;
}
}
Example: Leap Year Decider
public static boolean isLeap(int year) {
if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else if (year % 4 == 0) {
return true;
}
return false;
}
return false;
at the end of the method. If any of the conditions above were satisfied, we would have already returned something, stopping the method before it reaches the last return false;
. return false;
. In this context, we know that this line is only run if none of the previous conditions were satisfied. This will not always be something we know for certain, so the last line might change what our code does. When in doubt, put an else around code that should only run if the previous conditions were false. Β© 2024 Fiveable Inc. All rights reserved.