← Back to Home

if Statement

The if statement in Java is a conditional control flow statement used to execute a block of code only when a specified condition is true. It is the foundation of decision-making logic in Java programs. This topic is essential for beginners, real-time coding, and interviews.

What Is the if Statement?

  • Evaluates a boolean expression
  • Executes code only if the condition is true
  • Skips the block if the condition is false

Basic Syntax

if (condition) {
    // code to execute if condition is true
}
          

Simple Example

int age = 20;
if (age >= 18) {
    System.out.println("Eligible to vote");
}
          

Why it matters: The code inside the block executes only when the condition is satisfied.

Condition Rules

  • Condition must be of type boolean
  • Relational and logical expressions are commonly used
  • Java does not allow non-boolean conditions
if (10 > 5) {     // ✅ valid
}
if (10) {         // ❌ invalid
}
          

if Statement Without Braces

Braces {} are optional when there is only one statement, but not recommended.

if (x > 0)
    System.out.println("Positive");
          

Best Practice: Always use braces for readability and safety.

Using if with Logical Operators

if (age >= 18 && hasId) {
    System.out.println("Entry allowed");
}
          

Using if with Method Calls

if (isValidUser()) {
    processLogin();
}
          

Nested if Statement

An if inside another if.

if (age >= 18) {
    if (hasLicense) {
        System.out.println("Can drive");
    }
}
          

Why it matters: Used for dependent conditions.

if with Assignment Expression (Interview Trap)

boolean flag;
if (flag = true) {   // ❌ always true
    System.out.println("Executed");
}
          

Correct usage:

if (flag == true) {
}
          

Common Use Cases

  • Validation logic
  • Authorization checks
  • Business rule enforcement
  • Error handling conditions

Common Beginner Mistakes

  • Forgetting braces
  • Using = instead of ==
  • Writing non-boolean conditions
  • Deep nesting reducing readability
  • Ignoring short-circuit behavior

Interview-Ready Answers

Short Answer

The if statement is used to execute code when a specified condition evaluates to true.

Detailed Answer

In Java, the if statement evaluates a boolean condition and executes the associated code block only when the condition is true. It is the primary control structure for decision-making and conditional logic.

Key Takeaway

The if statement is the foundation of decision-making in Java. Correct use ensures clear logic, safe execution, and maintainable code.