First of all, it makes no sense to initialize the test for a new String (), since the initialization block immediately assigns it something else. Anyway...
The ad indicates one alternative:
public class BlockTest { String test = "testString"; }
Other in constructor:
public class BlockTest { String test; public BlockTest () { test = "testString"; } }
These are two basic, general options.
For the initialization block, two main applications are used. The first is for anonymous classes that must execute some logic during initialization:
new BaseClass () { List<String> strings = new ArrayList<String>(); { strings.add("first"); strings.add("second"); } }
The second is for normal initialization, which must be performed before each constructor:
public class MediocreExample { List<String> strings = new ArrayList<String>(); { strings.add("first"); strings.add("second"); } public MediocreExample () { ... } public MediocreExample (int parameter) { ... } }
However, in both cases there are alternatives that do not use the initialization block:
new BaseClass () { List<String> strings = createInitialList(); private List<String> createInitialList () { List<String> a = new ArrayList<String>(); a.add("first"); a.add("second"); return a; } }
and
public class MediocreExample { List<String> strings; private void initialize () { strings = new List<String>(); strings.add("first"); strings.add("second"); } public MediocreExample () { initialize(); ... } public MediocreExample (int parameter) { initialize(); ... } }
There are many ways to do this, use the most appropriate method, and provide the most clear and convenient code.