if-else Statement
The if-else statement in Java is a decision-making control structure used to execute one block of code when a condition is true and another block when it is false. It allows programs to handle two alternative execution paths. This concept is fundamental for real-time logic and interviews.
What Is the if-else Statement?
- Evaluates a boolean condition
- Executes if block when condition is true
- Executes else block when condition is false
Basic Syntax
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Simple Example
int number = 10;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
Condition Rules
- Condition must return boolean
- Relational and logical expressions are commonly used
- Non-boolean conditions are not allowed
if (10 > 5) { } // ✅ valid
if (10) { } // ❌ invalid
if-else Without Braces
Braces {} can be omitted for single statements, but it is not recommended.
if (x > 0)
System.out.println("Positive");
else
System.out.println("Negative");
Best Practice: Always use braces to avoid logical errors.
if-else with Logical Operators
if (age >= 18 && hasId) {
System.out.println("Access granted");
} else {
System.out.println("Access denied");
}
Nested if-else
An if-else inside another if or else.
if (score >= 60) {
if (score >= 90) {
System.out.println("Grade A");
} else {
System.out.println("Grade B");
}
} else {
System.out.println("Fail");
}
if-else vs Ternary Operator
Using if-else
int max;
if (a > b) {
max = a;
} else {
max = b;
}
Using Ternary Operator
int max = (a > b) ? a : b;
Why it matters: Use ternary only for simple conditions.
Common Beginner Mistakes
- Using = instead of ==
- Forgetting braces
- Deep nesting reducing readability
- Using if-else for multiple conditions instead of else-if
- Writing complex logic inside conditions
Interview-Ready Answers
Short Answer
The if-else statement executes one block of code when a condition is true and another when it is false.
Detailed Answer
In Java, the if-else statement evaluates a boolean condition. If the condition is true, the if block is executed; otherwise, the else block is executed, allowing two alternative execution paths.
Key Takeaway
The if-else statement enables clear decision-making by handling true and false paths explicitly. Proper use improves code readability and correctness.