Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 8.3.2.1 ""Initializers for Class Variables"": |
...at run time,
static
variables that arefinal
and that are initialized with compile-time constant values are initialized first.
...
Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 12.4 ""Initialization of Classes and Interfaces"": |
Initialization of a class consists of executing its
static
initializers and the initializers forstatic
fields (class variables) declared in the class.
...
Code Block | ||
---|---|---|
| ||
public class Cycle { private static final Cycle c = new Cycle(); private final int balance; private static final int deposit = (int) (Math.random() * 100); // Random deposit public Cycle(){ balance = deposit - 10; // Subtract processing fee } public static void main(String[] args) { System.out.println(""The account balance is: "" + c.balance); } } |
Compliant Solution
...
Code Block | ||
---|---|---|
| ||
public class Cycle { private final int balance; private static final int deposit = (int) (Math.random() * 100); // Random deposit private static final Cycle c = new Cycle(); // Inserted after initialization of required fields public Cycle(){ balance = deposit - 10; // Subtract processing fee } public static void main(String[] args) { System.out.println(""The account balance is: "" + c.balance); } } |
Noncompliant Code Example
...
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] Sections [8.3.2.1, Initializers for Class Variables|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.2.1]; [12.4, Initialization of Classes and Interfaces|http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4] Puzzle 49: Larger Than Life \[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 665|http://cwe.mitre.org/data/definitions/665.html] ""Improper Initialization"" |
...
49. Miscellaneous (MSC) 49. Miscellaneous (MSC) MSC01-J. Avoid memory leaks