JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Checkout for Promo Codes

Program: Example for singleton class using static block.


Description:

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.


Code:
package com.java2novice.staticexmp;

public class MyStaticSingleton {

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

class MySingleton{
	
	private static MySingleton instance;
	
	static{
		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...");
	}
}

Output:
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 fail-fast in java?
A fail-fast system is nothing but immediately report any failure that is likely to lead to failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators. Incase, you have called iterator on a collection object, and another thread tries to modify the collection object, then concurrent modification exception will be thrown. This is called fail-fast.
Famous Quotations
Discipline is just choosing between what you want now and what you want most.
-- 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 © 2020 by Nataraja Gootooru. All Rights Reserved.