else
Keyword in Java
The else
keyword in Java is used to define a block of code that executes when the condition in the associated if
statement is false. It gives us a way to provide an alternate path of execution when the primary condition isn’t met.
Syntax of else
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Simple Example
public class ElseExample {
public static void main(String[] args) {
int number = 10;
if (number < 5) {
System.out.println("Number is less than 5");
} else {
System.out.println("Number is greater than or equal to 5");
}
}
}
Number is greater than or equal to 5
Since 10 is not less than 5, the condition in the if
block fails. Thus, the else
block gets executed.
Using else with User Input
import java.util.Scanner;
public class ElseWithInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote yet.");
}
}
}
Sample Output 1
Enter your age: 21
You are eligible to vote.
Sample Output 2
Enter your age: 16
You are not eligible to vote yet.
This shows how else
helps to create a fallback condition in real-world scenarios like input validation.
else without if – Is it Valid?
No, else
cannot be used independently. It must always be paired with an if
block. If used alone, the compiler will throw an error.
// Invalid usage
else {
System.out.println("This will cause a compilation error");
}
Compilation Error
ElseExample.java:3: error: 'else' without 'if'
Nested if-else with else
We can also use else
with nested conditions to create multi-way decision logic.
public class NestedElse {
public static void main(String[] args) {
int marks = 75;
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 75) {
System.out.println("Grade: B");
} else if (marks >= 50) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
}
}
Grade: B
The conditions are evaluated from top to bottom. When marks >= 75
is true, that block executes, and the rest are ignored.
Common Mistakes Using else
- Using
else
without a correspondingif
- Adding a semicolon after
if
condition — this can lead to unexpected behavior
// Mistaken semicolon after if
if (value > 0); {
System.out.println("This block always executes!");
}
Why it’s wrong:
The semicolon ends the if
prematurely, so the block below is always executed regardless of the condition.