What is an If-Else Statement?
The if-else statement allows your program to make decisions — execute different blocks of code based on whether a condition is true or false.
if (condition) {
// Executes when condition is TRUE
} else {
// Executes when condition is FALSE
}This is the foundation of all programming logic. Without conditions, programs would always execute the same code regardless of input.
The if Statement
The simplest form — executes a block only if the condition is true:
public class IfDemo {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
System.out.println("Program continues...");
}
}Output:
You are eligible to vote.
Program continues...If age were 15, the if block would be skipped and only "Program continues..." would print.
The if-else Statement
Provides an alternative path when the condition is false:
public class IfElseDemo {
public static void main(String[] args) {
int temperature = 35;
if (temperature > 30) {
System.out.println("It's a hot day. Stay hydrated! ☀️");
} else {
System.out.println("The weather is pleasant. Enjoy! 🌤️");
}
}
}Output:
It's a hot day. Stay hydrated! ☀️The if-else-if Ladder
When you have multiple conditions to check:
public class GradeCalculator {
public static void main(String[] args) {
int marks = 78;
char grade;
if (marks >= 90) {
grade = 'A';
} else if (marks >= 80) {
grade = 'B';
} else if (marks >= 70) {
grade = 'C';
} else if (marks >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Marks: " + marks);
System.out.println("Grade: " + grade);
}
}Output:
Marks: 78
Grade: CHow it works:
| Condition | marks = 78 | Result |
|---|---|---|
marks >= 90 | 78 >= 90? false | Skip |
marks >= 80 | 78 >= 80? false | Skip |
marks >= 70 | 78 >= 70? true | ✓ Execute this block |
| (remaining) | — | Not checked |
Important: Once a condition is true, its block executes and the remaining conditions are skipped entirely.
Nested If-Else
You can place if-else statements inside other if-else blocks:
public class NestedIfDemo {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive a car.");
} else {
System.out.println("You are old enough, but you need a license.");
}
} else {
System.out.println("You are not old enough to drive.");
}
}
}Output:
You can drive a car.Tip: Avoid deep nesting (more than 2-3 levels). Refactor into methods or use logical operators instead.
Logical Operators in Conditions
Combine multiple conditions using logical operators:
| Operator | Name | Description |
|---|---|---|
&& | AND | Both conditions must be true |
|| | OR | At least one condition must be true |
! | NOT | Reverses the condition |
public class LogicalDemo {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = false;
// AND — all must be true
if (age >= 18 && hasLicense) {
System.out.println("Can drive: Yes");
}
// OR — at least one must be true
if (hasLicense || hasInsurance) {
System.out.println("Has at least one document: Yes");
}
// NOT — reverses condition
if (!hasInsurance) {
System.out.println("Warning: No insurance!");
}
}
}Output:
Can drive: Yes
Has at least one document: Yes
Warning: No insurance!Nested if vs Logical AND
These two are equivalent:
// Nested if
if (age >= 18) {
if (hasLicense) {
System.out.println("Can drive");
}
}
// Logical AND (cleaner)
if (age >= 18 && hasLicense) {
System.out.println("Can drive");
}Ternary Operator (Short If-Else)
For simple if-else assignments, use the ternary operator:
// Syntax: variable = (condition) ? valueIfTrue : valueIfFalse;
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status); // Adult
// Equivalent to:
String status2;
if (age >= 18) {
status2 = "Adult";
} else {
status2 = "Minor";
}Nested Ternary (use sparingly)
int marks = 85;
String grade = (marks >= 90) ? "A" :
(marks >= 80) ? "B" :
(marks >= 70) ? "C" : "F";
System.out.println(grade); // BWarning: Nested ternary operators reduce readability. Use if-else-if for complex conditions.
Common Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 10 |
!= | Not equal to | x != 10 |
> | Greater than | x > 10 |
< | Less than | x < 10 |
>= | Greater than or equal | x >= 10 |
<= | Less than or equal | x <= 10 |
Comparing Strings
String name = "Java";
// ✗ WRONG — compares references, not values
if (name == "Java") { ... }
// ✓ CORRECT — compares actual content
if (name.equals("Java")) {
System.out.println("Match!");
}
// Case-insensitive comparison
if (name.equalsIgnoreCase("java")) {
System.out.println("Case-insensitive match!");
}Practical Example: ATM Withdrawal
import java.util.Scanner;
public class ATMWithdrawal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double balance = 25000.0;
double minBalance = 500.0;
System.out.printf("Current Balance: ₹%.2f%n", balance);
System.out.print("Enter withdrawal amount: ₹");
double amount = scanner.nextDouble();
if (amount <= 0) {
System.out.println("❌ Invalid amount. Please enter a positive number.");
} else if (amount > balance - minBalance) {
System.out.printf("❌ Insufficient funds. Maximum withdrawal: ₹%.2f%n",
balance - minBalance);
} else if (amount % 100 != 0) {
System.out.println("❌ Amount must be a multiple of ₹100.");
} else {
balance -= amount;
System.out.printf("✅ ₹%.2f withdrawn successfully.%n", amount);
System.out.printf(" Remaining Balance: ₹%.2f%n", balance);
}
scanner.close();
}
}Sample Output:
Current Balance: ₹25000.00
Enter withdrawal amount: ₹5000
✅ ₹5000.00 withdrawn successfully.
Remaining Balance: ₹20000.00Common Mistakes
1. Using = instead of ==
int x = 5;
// if (x = 10) // ✗ Assignment, not comparison — compile error
if (x == 10) // ✓ Correct comparison2. Missing Braces
// Dangerous — only the first line is part of the if
if (age > 18)
System.out.println("Adult");
System.out.println("Can vote"); // Always executes!
// Safe — always use braces
if (age > 18) {
System.out.println("Adult");
System.out.println("Can vote");
}3. Comparing Strings with ==
String input = new String("hello");
// if (input == "hello") // ✗ May return false
if (input.equals("hello")) // ✓ Always correctSummary
ifexecutes code when a condition is trueif-elseprovides an alternative path for when the condition is falseif-else-ifladder checks multiple conditions in sequence- Use logical operators (
&&,||,!) to combine conditions - The ternary operator (
? :) is a shorthand for simple if-else - Always compare Strings with
.equals(), not== - Always use curly braces even for single-line if blocks
- Avoid deep nesting — refactor into methods or use logical operators