Welcome to The Coding College! In this tutorial, we’ll explore the else statement in Java. The else block is used in combination with the if
statement to specify a block of code to execute when the condition in the if
statement evaluates to false.
Why Use Else?
The else
statement ensures that even if the condition in the if
statement is not met, your program still performs an alternative action. This makes your code more dynamic and reliable.
Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example: Basic If … Else
public class ElseExample {
public static void main(String[] args) {
int temperature = 25;
if (temperature > 30) {
System.out.println("It's a hot day!");
} else {
System.out.println("The weather is pleasant.");
}
}
}
Output:
The weather is pleasant.
Example: Check Even or Odd
public class EvenOdd {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
Output:
7 is odd.
Example: Grading System
public class GradingSystem {
public static void main(String[] args) {
int marks = 45;
if (marks >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Output:
Fail
Nested Else
You can use multiple if ... else
statements for complex conditions, but make sure they are logically structured to avoid confusion.
Example: Nested If … Else
public class NestedElse {
public static void main(String[] args) {
int score = 65;
if (score >= 90) {
System.out.println("Excellent");
} else {
if (score >= 50) {
System.out.println("Good Job");
} else {
System.out.println("Try Again");
}
}
}
}
Output:
Good Job
Using Else with Logical Operators
Example: Multiple Conditions
public class ElseLogical {
public static void main(String[] args) {
int age = 15;
boolean hasTicket = false;
if (age >= 18 && hasTicket) {
System.out.println("You can watch the movie.");
} else {
System.out.println("You cannot watch the movie.");
}
}
}
Output:
You cannot watch the movie.
Practice Problems
- Write a program that checks if a number is positive or negative using
else
. - Create a program to determine if a person is eligible for a senior citizen discount (age 60 or above).
- Write a program to check if a year is a leap year or not using
if ... else
.
Tips for Using Else
- Default Behavior: Always include an
else
block to handle unexpected or default scenarios. - Keep It Simple: Avoid overly complex conditions in a single
if ... else
statement. - Readability: Write conditions and messages that are self-explanatory to improve code readability.
Conclusion
The else statement complements the if
statement by handling cases where the condition is not met. It’s an essential feature for building flexible and robust Java applications.
For more programming tutorials and examples, visit The Coding College and expand your coding knowledge! 🚀