How to Use Static Blocks in Java


In this example we will show how to use static blocks in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.List;

public class StaticBlockExample {
	private static List list;
    
	// static block
    static{
        list = new ArrayList();
        list.add(1);
        list.add(2);
    }
     
    public static void main(String a[]){
    	StaticBlockExample s = new StaticBlockExample();
        s.testList();
    }
         
    public void testList(){
        System.out.println(list);
    }
}

Output:

[1, 2]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments