class
Static Initialization Block example
In this example we shall show you how to use a static block for initialization of a classe’s fields. To show how a static block works in a class we have performed the following steps:
- We have created a class
StaticInitializationBlock
that has a static int array initialized with 10 fields. - It uses a static block, where it puts to each one of the array fields a random int value, using
random()
API method of Math multiplied by 100. - It has a method
void values()
that prints the fields of the array. - We create a new
StaticInitializationBlock
object and call itsvalues()
method to get its array’s fields. - We create another
StaticInitializationBlock
object and callvalues()
method again. - Since the array is static all instances have the same values to the array,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; class StaticInitializationBlock { static int[] val = new int[10]; static { System.out.println("Running initialization block."); for (int i = 0; i < val.length; i++) { val[i] = (int) (100.0 * Math.random()); } } void values() { for (int i = 0; i < val.length; i++) { System.out.print(" " + val[i]); } System.out.println(); } public static void main(String[] args) { //Instantiate this class StaticInitializationBlock staticBlock = new StaticInitializationBlock(); staticBlock.values(); //Create a new instance of the class //Notice that the values remain the same! staticBlock = new StaticInitializationBlock(); staticBlock.values(); } }
Output:
Running initialization block.
88 79 87 14 8 87 67 28 86 69
88 79 87 14 8 87 67 28 86 69
Ok, now we can change the code as follows. We print the array’s fields inside the static initialization block.
package com.javacodegeeks.snippets.core; class StaticInitializationBlock { static int[] val = new int[10]; static { System.out.println("Running initialization block."); for (int i = 0; i < val.length; i++) { val[i] = (int) (100.0 * Math.random()); } for (int i = 0; i < val.length; i++) { System.out.print(" " + val[i]); } System.out.println(); } void values() { for (int i = 0; i < val.length; i++) { System.out.print(" " + val[i]); } System.out.println(); } public static void main(String[] args) { //Instantiate this class //StaticInitializationBlock staticBlock = new StaticInitializationBlock(); //staticBlock.values(); //Create a new instance of the class //Notice that the values remain the same! //staticBlock = new StaticInitializationBlock(); //staticBlock.values(); } }
Output:
Running initialization block.
73 31 42 43 62 64 38 88 62 69
Notice that the code in the static block is executed without any code invoked inside main.
This means that you can execute code without a main! That’s cool !
This was an example of how to use a static block for initialization of a classe’s fields in Java.