When you need to perform a complicated initialization of a ``++static++`` member, it should be done in a ``++static++`` initializer block. That's because such blocks are only executed when the class is loaded into the JVM. That is, they run only once, and that happens before any instances are created. Non-``++static++`` blocks, on the other hand, run once for each instance that's created, so any ``++static++`` members "initialized" in such a block will be re-set for each new instance.


== Noncompliant Code Example

----
public class MyClass {
  private static List<String> names = new ArrayList<>();

  {
    names.add("foo");  // Noncompliant
  }
----


== Compliant Solution

----
public class MyClass {
  private static List<String> names = new ArrayList<>();

  static {
    names.add("foo");
  }
----


ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
