Empty If Body

ID

java.empty_if_body

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:1071, reliability

Description

Reports if statements whose then-branch is empty (either a bare semicolon or an empty block).

Rationale

An empty if body is almost always a bug. A stray semicolon after the if condition turns the intended body into a separate statement that runs unconditionally. Even when the empty block is intentional, the code should contain a comment explaining why the condition is checked but nothing is done.

// Bad -- stray semicolon
if (i < 0);                   // empty body!
    System.out.println("negative");  // always runs

// Bad -- empty block
if (i < 0) {
}

Remediation

Remove the stray semicolon or add the intended body:

// Good
if (i < 0) {
    System.out.println("negative");
}