⬅ Previous Topic
Java double KeywordNext Topic ⮕
Java enum Keyword⬅ Previous Topic
Java double KeywordNext Topic ⮕
Java enum Keywordelse
Keyword in JavaThe 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.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
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.
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.");
}
}
}
Enter your age: 21
You are eligible to vote.
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.
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");
}
ElseExample.java:3: error: 'else' without 'if'
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.
else
without a corresponding if
if
condition — this can lead to unexpected behavior// Mistaken semicolon after if
if (value > 0); {
System.out.println("This block always executes!");
}
The semicolon ends the if
prematurely, so the block below is always executed regardless of the condition.
⬅ Previous Topic
Java double KeywordNext Topic ⮕
Java enum KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.