Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

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 are final 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 for static fields (class variables) declared in the class.

...

Code Block
bgColor#FFcccc
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
bgColor#ccccff
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

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C++ Secure Coding Standard as DCL14-CPP. Do not make assumptions about the order of global variable initialization across translation units.

...

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