Introduction
The Java if-else statement is one of the most commonly used decision-making statements in Java programming. While the if statement executes a block of code only when a condition is true, the if-else statement provides two possible execution paths: one when the condition is true and another when it is false.
For example:
- If the entered password is correct, allow the user to log in; otherwise, display an error message.
- If a student scores at least 40 marks, display “Pass”; otherwise, display “Fail.”
In this tutorial, you’ll learn everything about the Java if-else statement, including its syntax, working mechanism, examples, real-life applications, common mistakes, best practices, and interview questions.
What is Java if-else Statement?
The Java if-else statement is a conditional statement that executes one block of code when a condition is true and another block of code when the condition is false.
It ensures that exactly one of the two blocks is executed.
Working Logic
- If the condition is true, Java executes the if block.
- If the condition is false, Java executes the else block.
This makes programs more dynamic and capable of handling different scenarios.
Example
int age = 20;
if (age >= 18) {
System.out.println("Eligible to Vote");
} else {
System.out.println("Not Eligible to Vote");
}
Output
Since the condition age >= 18 is true, Java executes the if block and ignores the else block.
Syntax
The syntax of the Java if-else statement is simple and easy to understand.
if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}
Explanation
- if is a Java keyword.
- condition must evaluate to either true or false.
- The if block executes when the condition is true.
- The else block executes when the condition is false.
- Only one block executes during each program run.
Flow of Java if-else Statement
The execution process is as follows:
- Java evaluates the condition.
- If the condition is true, execute the if block.
- Otherwise, execute the else block.
- Continue executing the remaining program.
Flow:
Condition
|
----------------
| |
True False
| |
Execute if Execute else
| |
----------------
|
Continue Program
Example 1: Check Even or Odd Number
public class Main {
public satic void main(String[] args) {
int number = 15;
if (number % 2 == 0) {
System.out.println("Even Number");
} else {
System.out.println("Odd Number");
}
}
}
Output
Example 2: Student Result
public class Main {
public static void main(String[] args) {
int marks = 72;
if (marks >= 40) {
System.out.println("Student Passed");
} else {
System.out.println("Student Failed");
}
}
}
Output
Example 3: Age Verification
public class Main {
public static void main(String[] args) {
int age = 16
if (age >= 18) {
System.out.println("Eligible for Driving License");
} else {
System.out.println("Not Eligible");
}
}
}
Output
Example 4: Positive or Negative Number
int number = -8;
if (number >= 0) {
System.out.println("Positive Number");
} else {
System.out.println("Negative Number");
}
Output
Example 5: Login Authentication
boolean isLoggedIn = false;
if (isLoggedIn) {
System.out.println("Welcome User");
} else {
System.out.println("Please Login");
}
Output
Operators Commonly Used with if-else
The if-else statement is commonly used with comparison and logical operators.
| Operator | Description | Example |
|---|---|---|
| == | Equal to | age == 18 |
| != | Not equal | age != 18 |
| > | Greater than | marks > 50000 |
| < | Less than | marks < 40 |
| >= | Greater than or equal | salary >= 1000 |
| <= | Less than or equal | price <= 100 |
| && | VLogical AND | age > 18 && citizen |
| || | Logical OR | admin || manager |
| ! | Logical NOT | !isLoggedIn |
Real-life Examples
1. ATM Withdrawal
int balance = 8000;
int withdraw = 9000;
if (balance >= withdraw) {
System.out.println("Transaction Successful");
} else {
System.out.println("Insufficient Balance");
}
2. Online Shopping Discount
double amount = 6500;
if (amount >= 5000) {
System.out.println("Free Shipping Available");
} else {
System.out.println("Delivery Charges Applied");
}
3. Employee Bonus
nt experience = 6;
if (experience >= 5) {
System.out.println("Bonus Approved");
} else {
System.out.println("Not Eligible for Bonus");
}
4. Temperature Warning
int temperature = 38;
if (temperature > 35) {
System.out.println("Heat Alert");
} else {
System.out.println("Normal Weather");
}
5. Password Validation
String password = "Java123";
if (password.equals("Java123")) {
System.out.println("Login Successful");
} else {
System.out.println("Invalid Password");
}
Advantages of Java if-else Statement
- Makes applications interactive.
- Handles both true and false conditions.
- Improves decision-making in programs.
- Easy to read and understand.
- Essential for implementing business logic.
- Widely used in web, desktop, and mobile applications.
- Reduces unnecessary code execution.
Common Mistakes
1. Using Assignment (=) Instead of Comparison (==)
Incorrect:
if (age = 18) {
}
Correct:
if (age == 18) {
}
2. Missing Curly Braces
Incorrect:
if (marks >= 40)
System.out.println("Pass");
System.out.println("Congratulations");
else
System.out.println("Fail");
Correct:
if (marks >= 40) {
System.out.println("Pass");
System.out.println("Congratulations");
} else {
System.out.println("Fail");
}
3. Extra Semicolon After if
Incorrect:
if (marks >= 40);
{
System.out.println("Pass");
}
The semicolon ends the if statement, causing the block to execute every time.
Correct:
if (marks >= 40) {
System.out.println("Pass");
}
4. Using Non-Boolean Conditions
Incorrect:
int number = 10;
if (number) {
}
Correct:
if (number > 0) {
}
5. Comparing Strings with ==
Incorrect:
String name = "Java";
if (name == "Java") {
System.out.println("Correct");
}
Correct:
if (name.equals("Java")) {
System.out.println("Correct");
}
Using equals() compares the actual contents of the strings rather than their object references.
Best Practices
- Always write meaningful conditions.
- Use braces {} even for a single statement.
- Keep conditions simple and easy to read.
- Use equals() to compare strings.
- Avoid deeply nested if-else statements.
- Test both true and false execution paths.
- Use comments where complex business logic is involved.
Difference Between if and if-else
| Feature | if Statement | if Statement |
|---|---|---|
| Execution | Executes only if the condition is true | Executes either the if block or the else block |
| False Condition | kips the block | Executes the else block |
| Number of Paths | One | Two |
| Use Case | Optional action | Alternative action |
Conclusion
The Java if-else statement is a fundamental decision-making construct that enables programs to perform different actions based on whether a condition is true or false. It is one of the first concepts every Java developer should master because it forms the foundation of application logic.
In this guide, you learned what the Java if-else statement is, its syntax, execution flow, practical examples, real-world applications, commonly used operators, advantages, common mistakes, best practices, and frequently asked interview questions.