Design Patterns

 Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time.

More reading:

Java Singleton Pattern

Java Singleton Pattern is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category.

From the definition, it seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns.

The implementation of Java Singleton pattern has always been a controversial topic among developers. Here we will learn about Singleton design pattern principles, different ways to implement the Singleton design pattern and some of the best practices for its usage.

Singleton Pattern
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
The singleton class must provide a global access point to get the instance of the class.
Singleton pattern is used for logging, drivers objects, caching and thread pool.
Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.
Java Singleton Pattern Implementation
To implement a Singleton pattern, we have different approaches but all of them have the following common concepts.

Private constructor to restrict instantiation of the class from other classes.
Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
In further sections, we will learn different approaches of Singleton pattern implementation and design concerns with the implementation.

Eager initialization
Static block initialization
Lazy Initialization
Thread Safe Singleton
Bill Pugh Singleton Implementation
Using Reflection to destroy Singleton Pattern
Enum Singleton
Serialization and Singleton

1. Eager initialization
In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.

Here is the implementation of the static initialization singleton class.

package com.journaldev.singleton;

public class EagerInitializedSingleton {

private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}

public static EagerInitializedSingleton getInstance(){
return instance;
If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections, etc. We should avoid the instantiation until unless client calls the getInstance method. Also, this method doesn’t provide any options for exception handling.

2. Static block initialization
Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.

package com.journaldev.singleton;

public class StaticBlockSingleton {

private static StaticBlockSingleton instance;

private StaticBlockSingleton(){}

//static block initialization for exception handling
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException(“Exception occured in creating singleton instance”);

public static StaticBlockSingleton getInstance(){
return instance;
Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create a Singleton class that supports lazy initialization.

Read: Java static

3. Lazy Initialization
Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.

package com.journaldev.singleton;

public class LazyInitializedSingleton {

private static LazyInitializedSingleton instance;

private LazyInitializedSingleton(){}

public static LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new LazyInitializedSingleton();
return instance;
The above implementation works fine in case of the single-threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if condition at the same time. It will destroy the singleton pattern and both threads will get the different instances of the singleton class. In next section, we will see different ways to create a thread-safe singleton class.

4. Thread Safe Singleton
The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.

package com.journaldev.singleton;

public class ThreadSafeSingleton {

private static ThreadSafeSingleton instance;

private ThreadSafeSingleton(){}

public static synchronized ThreadSafeSingleton getInstance(){
if(instance == null){
instance = new ThreadSafeSingleton();
return instance;

Above implementation works fine and provides thread-safety but it reduces the performance because of the cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization). To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of a singleton class is created.

The following code snippet provides the double-checked locking implementation.

public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
return instance;
Read: Thread Safe Singleton Class

5. Bill Pugh Singleton Implementation
Prior to Java 5, java memory model had a lot of issues and the above approaches used to fail in certain scenarios where too many threads try to get the instance of the Singleton class simultaneously. So Bill Pugh came up with a different approach to create the Singleton class using an inner static helper class. The Bill Pugh Singleton implementation goes like this;

package com.journaldev.singleton;

public class BillPughSingleton {

private BillPughSingleton(){}

private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();

public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.

This is the most widely used approach for Singleton class as it doesn’t require synchronization. I am using this approach in many of my projects and it’s easy to understand and implement also.

Read: Java Nested Classes

6. Using Reflection to destroy Singleton Pattern
Reflection can be used to destroy all the above singleton implementation approaches. Let’s see this with an example class.

package com.journaldev.singleton;

import java.lang.reflect.Constructor;

public class ReflectionSingletonTest {

public static void main(String[] args) {
EagerInitializedSingleton instanceOne = EagerInitializedSingleton.getInstance();
EagerInitializedSingleton instanceTwo = null;
try {
Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
//Below code will destroy the singleton pattern
instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
} catch (Exception e) {

When you run the above test class, you will notice that hashCode of both the instances is not same that destroys the singleton pattern. Reflection is very powerful and used in a lot of frameworks like Spring and Hibernate, do check out Java Reflection Tutorial.

7. Enum Singleton
To overcome this situation with Reflection, Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. Since Java Enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.

package com.journaldev.singleton;

public enum EnumSingleton {


public static void doSomething(){
//do something
Read: Java Enum

8. Serialization and Singleton
Sometimes in distributed systems, we need to implement Serializable interface in Singleton class so that we can store its state in the file system and retrieve it at a later point of time. Here is a small singleton class that implements Serializable interface also.

package com.journaldev.singleton;


public class SerializedSingleton implements Serializable{

private static final long serialVersionUID = -7604766932017737115L;

private SerializedSingleton(){}

private static class SingletonHelper{
private static final SerializedSingleton instance = new SerializedSingleton();

public static SerializedSingleton getInstance(){
return SingletonHelper.instance;

The problem with serialized singleton class is that whenever we deserialize it, it will create a new instance of the class. Let’s see it with a simple program.

package com.journaldev.singleton;


public class SingletonSerializedTest {

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
SerializedSingleton instanceOne = SerializedSingleton.getInstance();
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(

//deserailize from file to object
ObjectInput in = new ObjectInputStream(new FileInputStream(
SerializedSingleton instanceTwo = (SerializedSingleton) in.readObject();

System.out.println(“instanceOne hashCode=”+instanceOne.hashCode());
System.out.println(“instanceTwo hashCode=”+instanceTwo.hashCode());


The output of the above program is;

instanceOne hashCode=2011117821
instanceTwo hashCode=109647522
So it destroys the singleton pattern, to overcome this scenario all we need to do it provide the implementation of readResolve() method.

protected Object readResolve() {
return getInstance();
After this, you will notice that hashCode of both the instances is same in the test program.

/* */

Top 25 Java Interview Questions and Answers in 2020

Introduction to Java


Java is the most widely used and deployed language in the world. Created by James Gosling, Patrick Naughton and Mike Sheridan in 1991 while they were working with Netscape Communications, Java is now one of the three core technologies in the world of web. Being the high-level language, Java has made its mark in the IT industry with its first-class functions and holds a bright future.


Why is Java important?


In Java, the primary advantage is that it eliminates the need for recompilation. It enables developers to write code that runs everywhere making it easier and feasible for them to perform their tasks.

Regardless of the architecture of a system, Java compiled code can run on any JVM (Java virtual machine). This makes it one of the foremost widely-used programming languages. Java is a class-based and object-oriented programming language.

If you are aspiring to acquire this skill and make a career as a Java developer, you must consider taking up the Java course training from a reputed training provider and get certified.

Here, in this Java Interview Questions article, we have listed out the most important Java Interview Questions and Answers which will prepare you for any Java interview process.

For professionals with good knowledge of Java programming, looking for job opportunities and interviews, we have something interesting for you.

Here’s an updated list of top Java interview questions and answers that’ll help you in Java interviews.


Java Interview Questions and Answers – Set 1:


  1. Define class in Java?


In Java, a class is a template used to create objects and define the data type of them. It acts as a building block for Java language-oriented system.


  1. Explain the difference between dynamic and static loading?


Static class loading involves the creation of objects and instances using new keywords and dynamic class loading is done when the name of the class is not known at compile time.


  1. What is multi-threading?


It is a programming concept that allows to run multiple tasks within one single program in a concurrent manner.


  1. When and by whom was Java developed?


Java was developed in 1995 by James Gosling.


Java Interview Questions and Answers – Set 2:


  1. What do JVM, JRE, and JDK stand for?


  • JVM stands for Java Virtual Machine.
  • JRE stands for Java Runtime Environment.
  • JDK stands for Java Development Kit


  1. Does Java use pointers?


No, Java doesn’t use pointers. It has tough security. Instead of pointers, references are used in Java as they are safer and secure when compared to a pointer.


  1. Explain the steps involved in connecting to a database in java?


Below are the steps to connect to a database in Java,

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection


  1. Explain the functions of JVM and JRE?


The function of JVM is to offer a runtime environment for Java Byte Codes to be executed. And JRE includes the sets of files required by JVM during its runtime.


  1. Explain the difference between overloading and overriding?


Overloading occurs when there are two methods of the same name but different properties.

When there are two methods of the same name and properties, one is in the child class and the other is in the parent class, overriding occurs.


Java Interview Questions and Answers – Set 3:


  1. What is the default size of load factor in hashing based collection?


The default size is 0.75 and the default capacity is computed as


Initial capacity * Load factor.



  1. What is a package?


A Package is a collection of related classes and interfaces.


  1. What is the superclass of all exception classes?

Java.lang.Throwable is the superclass of all exception classes. In Java, all exception classes are derived from this base class.


  1. Explain the difference between equals() and = =?

Equals() method is used for checking equality of two objects defined by business logic.

“==” aka the equality operator is used to compare objects and primitives.



  1. State two differences between inner class and subclass

Inner classes must be in the same file whereas the subclasses can be in different files.

And subclasses have the methods of their parent class, but the inner classes can get the methods they want.


Java Interview Questions and Answers – Set 4:


  1. How are destructors defined in Java?

Java has its own garbage collection. This means that no destructors are required to be defined in Java. Destruction of objects is an automated process that is performed by the garbage collection mechanism.


  1. Define JSON

JSON is an acronym for JavaScript Object Notation. It uses the JavaScript syntax. The format in JSON is text only.


  1. What is the most important feature of Java?

The most important feature of Java is that it is a platform-independent language.


  1. What is an anonymous class?

The class that is defined in a single line of code using new keyword and without a name is an anonymous class.


  1. What is a JVM?

JVM is a Java Virtual Machine which is a runtime environment for the compiled java class files.


Java Interview Questions and Answers – Set 5:


  1. Can a dead thread be started again?

No, a thread that is in the dead state can’t be started again.


  1. Are arrays of primitive data types?

No. In Java, Arrays are objects.


  1. What are constructors in Java?

In Java, the constructor is a block of code which is used to initialize an object.


  1. What are the types of constructors?

There are two types of constructors:

  1. Default constructor
  2. Parameterized constructor


  1. Explain garbage collection in Java

In Java, when an object is longer used or referenced, garbage collection is called and the object is destroyed automatically.


  1. What’s the difference between Stack and Queue?

The difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle and a queue is based on FIFO (First In First Out) principle.


Java Interview tips


Having discussed the list of important Java Interview Questions and Answers, here we have listed some quick basic interview tips to help you ace the Java interview,

  • Be punctual and show up on time.
  • Be confident and communicate effectively
  • Avoid using slang words and fillers.
  • Read the job description and research about the company.
  • Listen carefully and take time before answering. Make sure your answers are relevant to the questions asked.
  • Dress and behave professionally.
  • Avoid interrupting the interviewer.
  • Carry all the essential documents.
  • Understand the job requirements and explain how you can fulfill them.
  • Thank the interviewer for his/her time. Ask for feedback and be open to constructive criticism too.


If you want to learn Java online, you can sign up for the course on Sprintzeal’s E-learning platform and take up their Java online course to get certified.




JavaScript is a vast topic. The list of Java interview questions and answers could be endless. But we hope you’ve found this comprehensive list of Java interview questions and answers we made for you informative and helpful.

To ensure you are well versed with all the Java programming related concepts, you can take up Java training and add the certification to your resume. Sprintzeal is a global training provider offering a wide range of training and certifications for professionals. You can get an overview and practical knowledge of Java concepts with our Java certification training. You get trained by our industry expert and accredited trainers. And the skills acquired from our Java training will give you an edge over other candidates when you attend interviews.

For more Java training and certification related details, you can reach us at support@sprintzeal or chat with our course expert. If you’re looking for other training and certifications to enhance your career, you can explore all courses offered by us and request for a trial.

If you are encountering any difficulties with these java interview questions, feel free to reach us. Besides this Java Interview Questions Blog, if you want to gain more knowledge about the programming language, you can get in touch with our trainers and opt for the Java training program.

So this leads us to the end of the blog for Java interview questions. The questions you were exposed to in this Java Interview Questions blog remain the most commonly asked questions by the recruiters in the industry. We are certain that these sets of Java Interview Questions will be of great help to you if you are preparing for interviews.


/* */