Java if Statement - Complete Guide
Introduction to if Statement
The if statement in Java executes a block of code only when its condition evaluates to true. It's one of the most fundamental control flow tools in Java.
By using if statements, programs can make decisions and adapt behavior depending on runtime conditions.
Basic if Syntax
The if statement starts with the if keyword, followed by a boolean condition in parentheses. If the condition is true, the code block inside curly braces runs.
Example
public class IfStatement {
public static void main(String[] args) {
int number = 10;
// Simple if statement
if (number > 0) {
System.out.println("The number is positive.");
}
// Single statement if (braces are optional but recommended)
if (number % 2 == 0)
System.out.println("The number is even.");
// Multiple conditions with logical operators
int age = 25;
if (age >= 18 && age <= 65) {
System.out.println("You are an adult of working age.");
}
// Using boolean variables in conditions
boolean isRaining = true;
boolean hasUmbrella = false;
if (isRaining && !hasUmbrella) {
System.out.println("You will get wet!");
}
// Nested if statements
int score = 85;
if (score >= 50) {
System.out.println("You passed!");
if (score >= 80) {
System.out.println("With distinction!");
}
}
}
}
Output
The number is positive. The number is even. You are an adult of working age. You will get wet! You passed! With distinction!
Comparison Operators in if Statements
Conditions in if statements often use comparison operators to compare values. These operators return true or false, determining whether the block runs.
Example
public class ComparisonOperators {
public static void main(String[] args) {
int a = 10, b = 5, c = 10;
if (a == c) {
System.out.println("a is equal to c");
}
if (a != b) {
System.out.println("a is not equal to b");
}
if (a > b) {
System.out.println("a is greater than b");
}
if (b < a) {
System.out.println("b is less than a");
}
if (a >= c) {
System.out.println("a is greater than or equal to c");
}
if (b <= a) {
System.out.println("b is less than or equal to a");
}
int age = 25;
boolean hasLicense = true;
if (age >= 18 && hasLicense) {
System.out.println("You can drive a car.");
}
if (age < 18 || !hasLicense) {
System.out.println("You cannot drive a car.");
}
}
}
Output
a is equal to c a is not equal to b a is greater than b b is less than a a is greater than or equal to c b is less than or equal to a You can drive a car.
Common Pitfalls and Best Practices
- ✅ Always use curly braces `{}` for clarity, even with one statement
- ✅ Write conditions with meaningful variable names
- ✅ Keep nesting shallow by using else if or early returns
- ✅ Use parentheses to make precedence explicit
- ✅ Extract complex conditions into boolean variables for readability
- ✅ Don’t confuse assignment (=) with equality (==)
- ✅ Test edge and boundary cases
- ✅ Avoid overly complicated conditions inside a single if