What is an if-else Statement?
The if-else statement in Java allows the program to make decisions and execute a block of code based on whether a condition is true or false.
It’s the foundation of decision-making in Java.
It’s the foundation of decision-making in Java.
Basic Syntax
java
Copy
Edit
if (condition) {
// code if condition is true
}
else {
// code if condition is false
}
Example:
java
Copy
Edit
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
}
else {
System.out.println("You are a minor.");
}
The if Statement
You can use an if statement alone without else.
Example:
java
Copy
Edit
int number = 10;
if (number > 0) {
System.out.println("Positive number");
}
If the condition is false, nothing happens.
The else Clause
The else clause runs only when the if condition is false.
Example:
java
Copy
Edit
int number = -5;
if (number > 0) {
System.out.println("Positive");
} else {
System.out.println("Not positive");
}
The if-else Statement Example
Example:
java
Copy
Edit
int marks = 75;
if (marks >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
Output: Pass
The if-else-if Ladder
This allows multiple conditions to be checked sequentially.
Example:
java
Copy
Edit
int score = 85;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 80) {
System.out.println("Grade B");
} else if (score >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
Nested if Statements
You can place one if inside another.
Example:
java
Copy
Edit
int number = 15;
if (number > 0) {
if (number % 2 == 0) {
System.out.println("Positive Even");
} else {
System.out.println("Positive Odd");
}
}
8. Comparison Operators in if-else
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
Example:
java
Copy
Edit
int x = 10, y = 20;
if (x != y) {
System.out.println("x is not equal to y");
}
Logical Operators with if-else
&& (AND)
|| (OR)
! (NOT)
Example:
java
Copy
Edit
int age = 25;
boolean hasID = true;
if (age >= 18 && hasID) {
System.out.println("Allowed to enter");
}
Boolean Conditions
Boolean values can directly be used.
Example:
java
Copy
Edit
boolean isAvailable = true;
if (isAvailable) {
System.out.println("Item is in stock.");
}
if-else with Strings
String comparisons should use .equals() instead of ==.
Example:
java
Copy
Edit
String city = "Delhi";
if (city.equals("Delhi")) {
System.out.println("Welcome to Delhi");
}
if-else with Characters
You can compare characters as with numbers
Example:
java
Copy
Edit
char grade = 'A';
if (grade == 'A') {
System.out.println("Excellent");
}
if-else in Loops
if-else is often used inside loops for decision-making.
Example:
java
Copy
Edit
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even");
} else {
System.out.println(i + " is odd");
}
}
Ternary Operator vs if-else
The ternary operator provides a shorthand.
Example:
java
Copy
Edit
int num = 5;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
Equivalent to:
java
Copy
Edit
if (num % 2 == 0) {
result = "Even";
} else {
result = "Odd";
}
Common Mistakes
Using == for Strings
Forgetting braces in multi-line blocks
Writing if (condition = true) instead of ==
Using Braces or Not?
For single statements, braces {} are optional but recommended.
Bad Practice:
java
Copy
Edit
if (x > 0)
System.out.println("Positive");
System.out.println("Always prints"); // misleading
Combining Multiple Conditions
Use && and || to combine checks.
Example:
java
Copy
Edit
int age = 30;
if (age >= 18 && age <= 35) {
System.out.println("Eligible");
}
Avoiding Deep Nesting
Instead of deep nesting, use return statements or switch.
Before:
java
Copy
Edit
if (a > 0) {
if (b > 0) {
if (c > 0) {
System.out.println("All Positive");
}
}
}
Better:
java
Copy
Edit
if (a <= 0 || b <= 0 || c <= 0) return;
System.out.println("All Positive");
switch vs if-else
Use switch for simple value-based decisions, if-else for range/complex logic.
if-else with Method Calls
Conditions can involve method returns.
Example:
java
Copy
Edit
public boolean isEven(int num) {
return num % 2 == 0;
}
if (isEven(10)) {
System.out.println("Even");
}
Real-life Examples
Login Example:
java
Copy
Edit
String user = "admin";
String pass = "1234";
if (user.equals("admin") && pass.equals("1234")) {
System.out.println("Login successful");
} else {
System.out.println("Login failed");
}
if-else in Exception Handling
Use if-else to validate before risky operations.
Example:
java
Copy
Edit
if (input != null) {
System.out.println(input.length());
} else {
System.out.println("Input is null");
}
Code Readability and Style
- Use clear indentation
- Add comments when logic is complex
- Avoid long if-else-if chains if possible
Performance Considerations
Evaluate the simplest/most likely condition first
Avoid unnecessary calculations in if conditions
Best Practices
- Keep conditions simple
- Use proper logical operators
- Favor readability over cleverness
- Avoid nested blocks if possible
- Prefer switch for fixed values
Conclusion
The if-else statement in Java is a crucial control structure that enables conditional execution of code blocks. Mastering its usage allows you to write smarter, clearer, and more efficient code. By understanding the various forms like nested conditions, logical operators, and best practices, you elevate your programming skills and prepare for real-world problem-solving.
Also Read:
0 Comments