JAVA CONDITIONS
Java else if statement
else if specifies a new condition to check when the previous if or else if condition was false.
What is else if for?
A regular if decides whether to run one block, while if and else lets you choose between two paths. When more outcomes are possible, insert one or more else if branches between them.
The program checks conditions from top to bottom and stops at the first one that evaluates to true.
else if syntax
if (sąlyga1) {
// Runs when sąlyga1 is true
} else if (sąlyga2) {
// Runs when sąlyga1 is false and sąlyga2 is true
} else {
// Runs when both conditions are false
}- The first branch of the chain always starts with the keyword
if. - You can add as many
else ifbranches as needed. - The final
elseis optional but handles all remaining cases. - At most one code block runs in a single chain.
Score evaluation example
The program can choose a different grade based on the score:
int taskai = 82;
if (taskai >= 90) {
System.out.println("Puikiai");
} else if (taskai >= 75) {
System.out.println("Gerai");
} else if (taskai >= 50) {
System.out.println("Išlaikyta");
} else {
System.out.println("Reikia pakartoti");
}
// Prints: Gerai The value 82 does not satisfy the first condition taskai >= 90, so the next condition is checked. taskai >= 75 is true, so “Gerai” (“Good”) is printed and the remaining branches are not checked.
The order of conditions matters
When condition ranges overlap, you usually check the strictest or most specific condition first. Otherwise a broader condition may stop the chain too early:
int taskai = 95;
// Incorrect order: the first condition is already true
if (taskai >= 50) {
System.out.println("Išlaikyta");
} else if (taskai >= 90) {
System.out.println("Puikiai");
}95 already satisfies the first condition taskai >= 50. The correct order would start with taskai >= 90.
When should you choose else if?
else if is suitable when each decision has a separate Boolean condition or checks a range of values. When one variable is compared with many exact values, a clearer option may be the switch statement.