Selection statements allow a Java program to choose which block of code to execute based on a condition.
Think of them as decision-makers. Just like we make decisions in daily lifeβ"If it is raining, take an umbrella; otherwise, go without one."βJava uses selection statements to make decisions during program execution.
Java provides two selection statements:
if-elseswitch
In this article, we'll focus on the if-else statement.
What Is the if Statement?
The if statement executes a block of code only when a specified condition evaluates to true.
Syntax
if (condition) {
// Executes when the condition is true
}
If the condition is false, the block is skipped.
Your First if Program
int age = 20;
if (age >= 18) {
System.out.println("Eligible to vote");
}
Output
Eligible to vote
Since the condition is true, the statement inside the if block executes.
Now change the value.
int age = 15;
if (age >= 18) {
System.out.println("Eligible to vote");
}
Output
No Output
The condition is false, so Java skips the block.
What Is the if-else Statement?
The if-else statement provides an alternative block of code when the condition is false.
Syntax
if (condition) {
// Executes when the condition is true
} else {
// Executes when the condition is false
}
Exactly one block is executed.
Example
int marks = 45;
if (marks >= 35) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
Output
Pass
Now change the marks.
int marks = 20;
if (marks >= 35) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
Output
Fail
Nested if Statements
An if statement can contain another if statement.
This is called a nested if.
Example
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("Can drive");
}
}
Output
Can drive
Nested if statements are useful when multiple conditions must be satisfied.
Rule 1: The Condition Must Be boolean
This is one of the biggest differences between Java and languages like C or C++.
In Java, the condition inside an if statement must evaluate to a boolean value.
Valid Example
int age = 25;
if (age > 18) {
System.out.println("Adult");
}
The expression
age > 18
returns a boolean (true or false).
Invalid Example
int age = 25;
if (age) {
System.out.println("Adult");
}
Compile-time error
incompatible types:
int cannot be converted to boolean
Why?
Java does not automatically convert numbers into boolean values.
Unlike C or C++:
-
0is not treated asfalse. - Non-zero values are not treated as
true.
Java requires an explicit boolean expression.
Rule 2: = vs == β The Classic Interview Trap
Many beginners accidentally use the assignment operator (=) instead of the equality operator (==).
Let's understand the difference.
Assignment (=)
boolean passed = false;
if (passed = true) {
System.out.println("Passed");
}
Output
Passed
Why?
The assignment
passed = true
stores true in the variable.
The assignment expression itself evaluates to true.
So the if condition becomes
if (true)
which always executes.
Equality (==)
boolean passed = false;
if (passed == true) {
System.out.println("Passed");
}
Output
No Output
Here, Java compares the value instead of assigning it.
Why Doesn't This Work?
int number = 10;
if (number = 20) {
}
Compile-time error
incompatible types:
int cannot be converted to boolean
The assignment returns an int, but if expects a boolean expression.
Interview Tip
Whenever you write an if condition, always double-check whether you intended to use
=- or
==
This mistake appears frequently in coding interviews.
Rule 3: Curly Braces ({}) Are Optional
If the body contains only one statement, curly braces may be omitted.
Example
if (true)
System.out.println("Hello");
This is perfectly valid.
The same program with braces.
if (true) {
System.out.println("Hello");
}
Both versions produce
Hello
Multiple Statements Require Braces
Incorrect
if (true)
System.out.println("Hello");
System.out.println("Rajesh");
Output
Hello
Rajesh
Only the first statement belongs to the if.
The second statement executes unconditionally.
Correct
if (true) {
System.out.println("Hello");
System.out.println("Rajesh");
}
Now both statements belong to the if block.
Variable Declarations Need Braces
Incorrect
if (true)
int age = 25;
Compile-time error
variable declaration not allowed here
A variable declaration cannot be the only statement controlled by an if without braces.
Correct
if (true) {
int age = 25;
System.out.println(age);
}
Rule 4: A Semicolon (;) Is a Valid Empty Statement
Many beginners accidentally write
if (true);
System.out.println("Hello");
Output
Hello
What Happened?
The semicolon acts as an empty statement.
The if controls only the empty statement.
if (true)
;
The println() statement is completely independent.
This is a very common programming mistake.
Common Beginner Mistakes
Forgetting Braces
Incorrect
if (marks >= 35)
System.out.println("Pass");
System.out.println("Congratulations!");
Many beginners expect both lines to execute only when the condition is true.
Only the first line belongs to the if.
Using = Instead of ==
Incorrect
if (passed = true)
Correct
if (passed == true)
or simply
if (passed)
Passing an Integer Instead of a Boolean
Incorrect
int number = 1;
if (number)
Correct
if (number != 0)
Accidentally Adding a Semicolon
Incorrect
if (marks >= 35);
System.out.println("Pass");
The condition has no effect because of the extra semicolon.
Best Practices
- Always use meaningful variable names such as
age,marks, orisEligible. - Use braces even for a single statement to improve readability.
- Avoid writing complex conditions inside an
if. - Use descriptive boolean variables like
isLoggedInorhasLicense. - Carefully distinguish between
=and==. - Never accidentally place a semicolon immediately after an
if.
Quick Memory Trick π§
Think of the if statement as asking a simple question:
"Is the condition true?"
If the answer is Yes, Java executes the if block.
Otherwise, it executes the else block (if present).
Remember:
- Condition β Must be
boolean - One statement β Braces optional
- Multiple statements β Braces required
-
=assigns a value -
==compares values
Key Takeaways
- The
ifstatement executes code only when its condition istrue. - The
if-elsestatement chooses between two blocks of code. - The condition must always evaluate to a boolean value.
- Java does not automatically convert numbers into booleans.
-
=performs assignment, while==performs comparison. - Curly braces are optional for a single statement but recommended.
- A semicolon (
;) is a valid empty statement and can introduce subtle bugs. - Nested
ifstatements allow multiple conditions to be checked.
If you found this guide helpful, leave a β€οΈ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)