CKTIS / Java
else — alternative if branch
else — alternative if branch: else supplies the alternative statement for the nearest preceding if whose boolean condition evaluated to false.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
elseelse supplies the alternative statement for the nearest preceding if whose boolean condition evaluated to false.
Use braces, especially for nested if statements, to make the else association explicit and keep edits safe.
Without braces, the dangling-else rule binds else to the nearest eligible if, regardless of indentation or author intent.
An else-if chain is nested statements rather than separate syntax; only the first branch whose condition is true executes.
For value 5, the inner if is false, so the nearest else assigns positive-odd; the outer else does not execute.
Examples
public class Main {
public static void main(String[] args) {
int value = 5;
String result;
if (value > 0)
if (value % 2 == 0)
result = "positive-even";
else
result = "positive-odd";
else
result = "not-positive";
System.out.println(result);
}
}
Result
positive-odd
For value 5, the inner if is false, so the nearest else assigns positive-odd; the outer else does not execute.