singleton class using static block in java

We can use static blocks to develop singleton class.static blocks will be execute only once,To create singleton class, make constructor as private, so that you can not create object from outside of the class.
there in static block we create try catch block.inside try block create the object of singleton class and in catch block we handle the exception.static blocks will be execute only once thats why singleton object created only once.

				
					public class StaticBlockSingleton {
	private static StaticBlockSingleton instance;

	private StaticBlockSingleton() {
	}

	static {
		try {
			instance = new StaticBlockSingleton();
		} catch (Exception e) {
			throw new RuntimeException("exception occured in creating singleton");
		}
	}

	public static StaticBlockSingleton getInstance() {
		return instance;
	}
}
				
			

Leave a Comment

Your email address will not be published. Required fields are marked *