Odd Check Fails for Negative Numbers

ID

java.odd_check_negative_safe

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

reliability, suspicious-comparison

Description

Reports the pattern x % 2 == 1 for checking whether a value is odd.

Rationale

The expression x % 2 == 1 only works correctly for positive numbers. In Java, the % operator preserves the sign of the dividend, so -3 % 2 evaluates to -1, not 1. This means the check incorrectly reports negative odd numbers as even.

// Bad - fails for negative numbers
if (x % 2 == 1) {
    // x = -3 would not enter here, even though -3 is odd
}

Remediation

Use x % 2 != 0 which works correctly for both positive and negative numbers.

// Good - handles negative numbers correctly
if (x % 2 != 0) {
    // x = -3 correctly enters here
}