DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 1: `if-else` Statement

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-else
  • switch

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
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

Output

Eligible to vote
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

Output

No Output
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Exactly one block is executed.


Example

int marks = 45;

if (marks >= 35) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
Enter fullscreen mode Exit fullscreen mode

Output

Pass
Enter fullscreen mode Exit fullscreen mode

Now change the marks.

int marks = 20;

if (marks >= 35) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
Enter fullscreen mode Exit fullscreen mode

Output

Fail
Enter fullscreen mode Exit fullscreen mode

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");
    }

}
Enter fullscreen mode Exit fullscreen mode

Output

Can drive
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

The expression

age > 18
Enter fullscreen mode Exit fullscreen mode

returns a boolean (true or false).


Invalid Example

int age = 25;

if (age) {
    System.out.println("Adult");
}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

incompatible types:
int cannot be converted to boolean
Enter fullscreen mode Exit fullscreen mode

Why?

Java does not automatically convert numbers into boolean values.

Unlike C or C++:

  • 0 is not treated as false.
  • 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");

}
Enter fullscreen mode Exit fullscreen mode

Output

Passed
Enter fullscreen mode Exit fullscreen mode

Why?

The assignment

passed = true
Enter fullscreen mode Exit fullscreen mode

stores true in the variable.

The assignment expression itself evaluates to true.

So the if condition becomes

if (true)
Enter fullscreen mode Exit fullscreen mode

which always executes.


Equality (==)

boolean passed = false;

if (passed == true) {

    System.out.println("Passed");

}
Enter fullscreen mode Exit fullscreen mode

Output

No Output
Enter fullscreen mode Exit fullscreen mode

Here, Java compares the value instead of assigning it.


Why Doesn't This Work?

int number = 10;

if (number = 20) {

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error

incompatible types:
int cannot be converted to boolean
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

This is perfectly valid.


The same program with braces.

if (true) {
    System.out.println("Hello");
}
Enter fullscreen mode Exit fullscreen mode

Both versions produce

Hello
Enter fullscreen mode Exit fullscreen mode

Multiple Statements Require Braces

Incorrect

if (true)
    System.out.println("Hello");
    System.out.println("Rajesh");
Enter fullscreen mode Exit fullscreen mode

Output

Hello
Rajesh
Enter fullscreen mode Exit fullscreen mode

Only the first statement belongs to the if.

The second statement executes unconditionally.


Correct

if (true) {

    System.out.println("Hello");

    System.out.println("Rajesh");

}
Enter fullscreen mode Exit fullscreen mode

Now both statements belong to the if block.


Variable Declarations Need Braces

Incorrect

if (true)

    int age = 25;
Enter fullscreen mode Exit fullscreen mode

Compile-time error

variable declaration not allowed here
Enter fullscreen mode Exit fullscreen mode

A variable declaration cannot be the only statement controlled by an if without braces.

Correct

if (true) {

    int age = 25;

    System.out.println(age);

}
Enter fullscreen mode Exit fullscreen mode

Rule 4: A Semicolon (;) Is a Valid Empty Statement

Many beginners accidentally write

if (true);

System.out.println("Hello");
Enter fullscreen mode Exit fullscreen mode

Output

Hello
Enter fullscreen mode Exit fullscreen mode

What Happened?

The semicolon acts as an empty statement.

The if controls only the empty statement.

if (true)
    ;
Enter fullscreen mode Exit fullscreen mode

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!");
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Correct

if (passed == true)
Enter fullscreen mode Exit fullscreen mode

or simply

if (passed)
Enter fullscreen mode Exit fullscreen mode

Passing an Integer Instead of a Boolean

Incorrect

int number = 1;

if (number)
Enter fullscreen mode Exit fullscreen mode

Correct

if (number != 0)
Enter fullscreen mode Exit fullscreen mode

Accidentally Adding a Semicolon

Incorrect

if (marks >= 35);

System.out.println("Pass");
Enter fullscreen mode Exit fullscreen mode

The condition has no effect because of the extra semicolon.


Best Practices

  • Always use meaningful variable names such as age, marks, or isEligible.
  • Use braces even for a single statement to improve readability.
  • Avoid writing complex conditions inside an if.
  • Use descriptive boolean variables like isLoggedIn or hasLicense.
  • 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 if statement executes code only when its condition is true.
  • The if-else statement 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 if statements 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)