Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
According to \[[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."

...

This noncompliant example contrives to calculate the account balance by subtracting the processing fee from the deposited amount, but fails miserably. The Cycle class object c is instantiated before the deposit field gets initialized. As a result, the constructor Cycle is invoked which computes the balance based on the initial value of deposit (0) rather than the random value. As a result, the balance always remains -10.

Wiki Markup
According to \[[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#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);	
  }
}

Risk Assessment

TODOInitialization cycles may lead to unexpected results.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC00-J

?? low ??

unlikely

?? medium

P??

L??

Automated Detection

...

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

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] Sections 
JLS JLS
8.3.2.1, Initializers for Class Variables
, JLS
; 12.4, Initialization of Classes and
Interfaces
Puzzlers, Traps 49 "be careful of class initialization cycles"
 Interfaces
\[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 49: Larger Than Life