JAVA.FINAL.STATIC.VAR

Use of nonfinal static variable

Vulnerability and risk

The JLS does not mandate complete initialization and safe publication of a variable even if a static initializer is used.

Mitigation and prevention

Ensure safe publication by declaring the static variable final.

Vulnerable code example

Copy
package com.klocwork;

public class JAVA_FINAL_STATIC_VAR_POSITIVE {
    static String out = "hello world";

    public static void main(String args[]) {
        System.out.println(out);
    }
}

Fixed code example

Copy
package com.klocwork;

public class JAVA_FINAL_STATIC_VAR_NEGATIVE {
    final static String out = "hello world";

    public static void main(String args[]) {
        System.out.println(out);
    }
}

External guidance