JAVA.UNINIT.LOOP_COUNTER

Loop counter in for statement not declared in initialization expression.

Vulnerability and risk

Unless there is an explicit reason, counter variables should be declared and initialized in the for statement's initialization expression to prevent unintended loop counter reuse.

Mitigation and prevention

Unless there is an explicit reason, counter variables must be declared and initialized in the for statement's initialization expression.

Example

Copy
class C05 {

    public void testOK() {
        for (int i = 0; i < 5; i++) { //OK
            //do something
        }
    }

    public void testNG() {
        int i = 0;
        for (i = 1; i < 5; i++) { //NG
            //do something
        }

    }

    public void testNG2() {
        int i = 0;
        for (; i < 5; i++) { //NG
            //do something
        }

    }

}