JAVA.LOOP.CTR.FLOAT

Do not use floating-point variables as loop counters

Vulnerability and risk

Floating-point variables may not represent decimals precisely and lead to unexpected outcomes when used as loop counters.

Mitigation and prevention

Do not use floating numbers when checking for loop conditions (use int/long). Use integers for loop counters.

Vulnerable code example

Copy
package com.klocwork;

public class JAVA_LOOP_CTR_FLOAT_POSITIVE {
    public static void test(String args[]) {
        for (float i = 0; i < 100; i++) {
            System.out.println("hello world");
        }        
    }
}

Fixed code example

Copy
package com.klocwork;

public class JAVA_LOOP_CTR_FLOAT_NEGATIVE {
    public static void test(String args[]) {
        for (int i = 0; i < 100; i++) {
            System.out.println("hello world");
        }        
    }
}

External guidance