Publish Your Article Here

Program: Example for singleton class using static block.


Since static blocks will be called only once, we can use static blocks to develop singleton class. Below example shows how to create singleton classes using static block. To create singleton class, make constructor as private, so that you cannot create object outside of the class. Create a private static variable of same class type, so that created object will be pointed to this reference. Now create static block, and create object inside static block. Since static block will be called only once, the object will be created only once.

package com.java2novice.staticexmp;

public class MyStaticSingleton {

	public static void main(String a[]){
		MySingleton ms = MySingleton.getInstance();

class MySingleton{
	private static MySingleton instance;
		instance = new MySingleton();
	private MySingleton(){
		System.out.println("Creating MySingleton object...");
	public static MySingleton getInstance(){
		return instance;
	public void testSingleton(){
		System.out.println("Hey.... Instance got created...");

Creating MySingleton object...
Hey.... Instance got created...
<< Previous Program 

List Of All Static Keyword Programs:

  1. Example for static variables and methods.
  2. Example for static block.
  3. Example for static block vs constructor.
  4. Example for singleton class using static block.
Knowledge Centre
What is servlet context?
The servlet context is an interface which helps to communicate with other servlets. It contains information about the Web application and container. It is kind of application environment. Using the context, a servlet can obtain URL references to resources, and store attributes that other servlets in the context can use.
Famous Quotations
Before you go and criticize the younger generation, just remember who raised them.
-- Unknown Author

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.