Versions Compared

Key

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

...

While this statement typically holds, it can be misleading as it does not account for instances that use values of static final fields initialized at a later stage. Even if a field is static final, it is not necessarily initialized at first gobefore being read.

Noncompliant Code Example

This noncompliant code example contrives to calculate the account balance by subtracting the processing fee from the deposited amount, but fails to do so. 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.

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);	
  }
}

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 the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], section 12.4 "Initialization of Classes and Interfaces":

...

This compliant solution changes the initialization order of the class Cycle so that the fields meant to be used in computations get duly initialized. As initialization cycles can become insidious when many classes are involved, proper care must be taken to inspect the control flow.

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);	
  }
}

As initialization cycles can become insidious when many classes are involved, proper care must be taken to inspect the control flow.

Noncompliant Code Example

...