Skip to main content

Java Design Patterns Interview Questions


Java Design Patterns Interview Questions




1. When will you use Strategy Design Pattern in Java?
Strategy pattern is very useful for implementing a family of algorithms. It is a behavioral design pattern. With Strategy pattern we can select the algorithm at runtime. We can use it to select the sorting strategy for data. We can use it to save files in different formats like- .txt, .csv, .jpg etc.
In Strategy pattern we create an abstraction, which is an interface through which clients interact with our system. Behind the abstraction we create multiple implementation of same interface with different algorithms. For a client, at runtime we can vary the algorithm based on the type of request we have received.
So we use Strategy pattern to hide the algorithm implementation details from client. In Java Collections.sort() method uses strategy design pattern.

2. What is Observer design pattern?
In Observer design pattern, there is a Subject that maintains the list of Observers that are waiting for any update on the Subject. Once there is an update in Subject it notifies all the observers for the change.
E.g. In real life, students are waiting for the result of their test. Here students are the observers and test is the subject. Once the result of test is known, testing organization notifies all the students about their result.
The most popular use of Observer pattern is in Model View Controller (MVC) architectural pattern. Main issue with Observer pattern is that it can cause memory leaks. The subject holds a strong reference to observers. If observers are not de-registered in time, it can lead to memory leak.

3. What are the examples of Observer design pattern in JDK?
In JDK there are many places where Observer design pattern is used. Some of these are as follows:
1.java.util.Observer, java.util.Observable
2.javax.servlet.http.HttpSessionAttributeListener
3.javax.servlet.http.HttpSessionBindingListener
4.All implementations of java.util.EventListener, and also in Swing packages
5.javax.faces.event.PhaseListener

4. How Strategy design pattern is different from State design pattern in Java?
State design pattern is a behavioral design pattern that is use for defining the state machine for an object. Each state of an object is defined in a child class of State class. When different actions are taken on an Object, it can change its state.
Strategy pattern is also a behavioral pattern, but it is mainly used for defining multiple algorithms. With same action of a client, the algorithm to be used can change.
Some people consider State pattern similar to Strategy pattern, since an Object changes its Strategy with different method invocations. But the main difference is that in State pattern internal state of an Object is one of the determining factors for selecting the Strategy for change of state.
Where as in Strategy pattern, client can pass some external parameter in input during method invocation that determines the strategy to be used at run time.
Therefore State pattern is based on the Object’s internal state, where as Strategy pattern is based on Client’s invocation. State pattern is very useful in increasing the maintainability of the code in a large code-base.

5. Can you explain Decorator design pattern with an example in Java?
Some people call Decorator pattern as Wrapper pattern as well. It is used to add the behavior to an object, without changing the behavior of other objects of same class.
One of the very good uses of Decorator pattern is in java.io package. We can have a FileInputStream to handle a File. To add Buffering behavior we can decorate FileInputStream with BufferedInputStream. To add the gzip behavior BufferedInputStream we can decorate it with GzipInputStream. To add serialization behavior to GzipInputStream, we can decorate it with ObjectInputStream.
E.g.
Open a FileInputStream:
FileInputStream fis = new FileInputStream("/myfile.gz");
Add buffering:
BufferedInputStream bis = new BufferedInputStream(fis);
Add Gzip:
GzipInputStream gis = new GzipInputStream(bis);
Add Serialization:
ObjectInputStream ois = new ObjectInputStream(gis);
So with each step we have decorated the FileInputStream with additional behavior.

6. What is a good scenario for using Composite design Pattern in Java?
Some of the good scenarios where Composite design pattern can be used are as follows:
Tree Structure: The most common use of Composite design pattern is Tree structure. If you want to represent data in a Tree data structure, Composite pattern can be used.
E.g. In an Organization, to a Manager has Employees. But Manager is also an Employee. If we start from CEO level, there is one big tree for the whole organization structure. Under that big tree there are many sub-trees. This can be easily represented with Composite design pattern.
Recursion: Another use of Composite design pattern is Recursion. If we have a Recursion based algorithm, we need data to be passed to algorithm in a data structure that treats individual objects and compositions at each level of recursion uniformly.
E.g. To implement a recursive Polynomial Solving algorithm, we can use Composite design pattern to store the intermediate results.
Graphics: Another good use of Composite design pattern is in Graphics. We can group shapes inside a composite and make higher-level groups of smaller groups of shapes to complete the graphics to be displayed on screen.

7. Have you used Singleton design pattern in your Java project?
Yes. Singleton is one of the most popular design patterns in enterprise level Java applications. Almost in every project we see some implementation of Singleton. With Singleton pattern we can be sure that there is only one instance of a class at any time in the application.

This helps in storing properties that have to be used in the application in a unique location.

8. What are the main uses of Singleton design pattern in Java project?
Some of the main uses of Singleton design pattern in Java are as follows:
Runtime: In JDK, java.lang.Runtime is a singleton-based class. There is only one instance of Runtime in an application. This is the only class that interfaces with the environment/machine in which Java process is running.
Enum: In Java, enum construct is also based on Singleton pattern. Enum values can be accessed globally in same way by all classes.
Properties: In an application it makes sense to keep only one copy of the properties that all classes can access. This can be achieved by making properties class Singleton so that every class gets same copy of properties.
Spring: In Spring framework, all the beans are by default Singleton per container. So there is only one instance of bean in a Spring IoC container. But Spring also provides options to make the scope of a bean prototype in a container.

9. Why java.lang.Runtime is a Singleton in Java?
In Java, java.lang.Runtime is implemented on Singleton design pattern. Runtime is the class that acts as an interface with the environment in which Java process is running. Runtime contains methods that can interact with the environment.
Like- totalmemory() method gives the total memory in JVM. maxMemory() method gives the maximum memory that JVM can use.
There is an exit() method to exit the Java process. We do not want multiple objects in JVM to have exit() method. Similarly there is gc() method that can run the Garbage Collector. With only one copy of gc() method, we can ensure that no other object can run the Garbage Collector when one instance of GC is already running.
Due to all these reasons there is only one copy of Runtime in Java. To ensure single copy of Runtime, it is implemented as a Singleton in Java.

10. What are the examples of Singleton design pattern in JDK?
In JDK there are many places where Singleton design pattern is used. Some of these are as follows:
java.lang.Runtime.getRuntime(): This method gives Runtime class that has only one instance in a JVM.
java.lang.System.getSecurityManager(): This method returns a SecurityManager for the current platform. java.awt.Desktop.getDesktop()

11. What is the way to implement a thread-safe Singleton design pattern in Java?
In Java there are many options to implement a thread-safe Singleton pattern. Some of these are as follows:
Double Checked Locking: This is the most popular methodto implement Singleton in Java. It is based on LazyInitialization. In this we first check the criteria for lockingbefore acquiring a lock to create an object. In Java we useit with volatile keyword.
Sample code:
class DoubleCheckSingleton {
private volatile HelloSingleton helloSingleton; // Use Volatile public HelloSingleton
getHelloSingleton() {
HelloSingleton result = helloSingleton;
if (result == null) {
synchronized(this) { // Synchronize for thread safety
result = helloSingleton;
if (result == null) {
result = new HelloSingleton();
helloSingleton = result;
}
}
}
return result;
}
}

Bill Pugh Singleton: We can also use the method by BillPugh for implementing Singleton in Java. In this we use anInner Static class to create the Singleton instance.Sample code:
public class SingletonBillPugh { // Inner class that holds instance
private static class InnerSingleton{
private static final SingletonBillPugh INSTANCE = new SingletonBillPugh();
} // Private constructor
private SingletonBillPugh(){}
public static SingletonBillPugh getInstance(){
return InnerSingleton.INSTANCE;
}
}
When first time SingletonBillPugh is loaded in memory, InnerSingleton is not loaded. Only when getInstance() method is called, InnerSingleton class is loaded and an Instance is created.
Enum: We can also use Java enum to create thread-safe implementation. Java enum values are accessible globally so these can be used as a Singleton.Sample Code:
public enum SingletonEnum {
INSTANCE; public static void doImplementation(){ ….. }
}

12. What is Template Method design pattern in Java?
It is a behavioral design pattern. We can use it to create an outline for an algorithm or a complex operation. We first create the skeleton of a program. Then we delegate the steps of the operation to subclasses. The subclasses can redefine the inner implementation of each step.
E.g. While designing a Game in Java, we can implement it as an algorithm with Template Method pattern. Each step in the game can be deferred to subclasses responsible for handling that step.
Let say we implement Monopoly game in Java. We can create methods like initializeGame(), makeMove(), endGame() etc. Each of these methods can be handled in subclasses in an independent manner.
We can use same algorithm for Chess game with same set of abstract methods. The subclass for Chess game can provide the concrete implementation of methods like initializeGame(), makeMove(),  endGame() etc.
Template Method pattern is very useful in providing customizable class to users. We can create the core class with a high level implementation. And our users can customize our core class in their custom subclasses.

13. What are the examples of Template method design pattern in JDK?
In JDK there are many places where Template method design pattern is used. Some of these are as follows:
1. In Java Abstract Collection classes like java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap implement a template for their corresponding Collection.
2. javax.servlet.http.HttpServlet: In the HttpServlet class all the doGet(), doPost() etc. methods send a HTTP 405 "Method Not Allowed" error to the response. This error response is like a Template that can be further customized for each of these methods.
3. In java.io package there are Stream and Writer classes like java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer that provide non-abstract methods. These methods are implementation of Template method design pattern.

14. Can you tell some examples of Factory Method design pattern implementation in Java?
Factory Method pattern is a creational design pattern. A Factory is an object that is used to create more objects. In general, a Factory object has methods that can be used to create a type of objects. Some people call it Factory Method design pattern as well.
Some of the examples of Factory Method pattern in JDK are:
Java.lang.Class.forName()
java.net.URLStreamHandlerFactory.createURLStreamHandler(String)
java.util.Calendar.getInstance()
java.util.ResourceBundle.getBundle()
java.text.NumberFormat.getInstance()
java.nio.charset.Charset.forName()
java.util.EnumSet.of()
javax.xml.bind.JAXBContext.createMarshaller()

15.What is the difference between Factory and Abstract Factory design pattern?
                       With Factory design pattern we can create concrete products of a  type that Factory can manufacture. E.g. If it is CarFactory, we can produce, Ford, Toyota, Honda, Maserati etc. With Abstract Factory design pattern we create a concrete implementation of a Factory. E.g. DeviceFactory can be Abstract and it can give us GoogleDeviceFactory, AppleDeviceFactory etc. With AppleDeviceFactory we will get products like- iPhone, iPad, Mac etc. With GoogleDeviceFactory we will get products likeNexus phone, Google Nexus tablet, Google ChromeBook etc. So it is a subtle difference between Factory and Abstract Factory design pattern. One way to remember is that within Abstract Factory pattern, Factory pattern is already implemented.

16. What is Open/closed design principle in Software engineering?
               Open/closed design principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”. Open/closed principle term was originated by Bertrand Meyer in his book Object Oriented Software Construction. As per this principle, if a module is available for extension then it is considered open. If a module is available for use by other modules then it is considered closed. Further Robert C. Martin has mentioned it as O in SOLID principles of Object Oriented design. It is used in State and Strategy design patterns. Context class is closed for modification. But new functionality can be added by writing new strategy code.

17. What is SOLID design principle?
                  SOLID word in SOLID design principle is an acronym for:
1. S: Single responsibility. A Class should have a single responsibility. 
2. O: Open-closed. Software entities should be open for extension but closed for modification. 
3. L: Liskov substitution. Objects in a program should be replaceable by subclasses of same type without any adverse impact. 
4. I: Interface segregation. Multiple client specific interfaces are preferable over single generic interface. 
5. D: Dependency inversion. Program should depend on abstract entities. It should not depend on concrete implementation of an interface. 
                      This principle was mentioned by Robert C. Martin. These are considered five basic principles of Object Oriented design. If we follow these principles, then we can create a stable program that is easy to maintain and can be extended over time.

18. What is Builder design pattern?
                  Builder design pattern is a creational design pattern. We can use  Builder pattern to create complex objects with multiple options. E.g. when we have to create a Meal in a restaurant we can use Builder pattern. We can keep adding options like- Starter, Drink, Main Course, and Dessert etc. to create complete meal. When a user selects other options of Starter, Drink Main Course, Dessert another type of meal is created. Main feature of Builder pattern is step-by-step building of a complex object with multiple options.

19. What are the different categories of Design Patterns used in Object Oriented Design?
             In Object Oriented design mainly three categories of design patterns are used. These categories are:
           Creational Design Patterns:

Builder
Factory MethodAbstract FactoryObject PoolSingletonPrototypeStructural Design Patterns:AdapterBridgeFaçadeDecoratorCompositeFlyweightProxyBehavioral Design Patterns:CommandIteratorChain of ResponsibilityObserverStateStrategyMediatorInterpreter


20. What is the design pattern suitable to access elements of a Collection?
             We can use Iterator design pattern to access the individual elements of a Collection. In case of an ordered collection we can get Iterator that returns the elements in an order.
             In Java there are many implementation of Iterator in Collections package. We have iterators like- Spliterator, ListIterator etc. that implement Iterator pattern.


21. What design pattern is suitable to add new features to an existing object?
               We can use Decorator design pattern to add new features to an existing object. With a Decorator we work on same object and return the same object with more features. But the structure of the object remains same since all the decorated versions of object implement same interface.

22. Which design pattern can be used when to decouple abstraction from the implementation?
                We can use Bridge design pattern to detach the implementation from the abstraction. Bridge is mainly used for separation of concern in design. We can create an implementation and store it in the interface, which is an abstraction. Where as specific implementation of other features can be done in concrete classes that implement the interface. Often Bridge design pattern is implemented by using Adapter pattern.
               E.g. we have Shape interface. We want to make Square and Circle shapes. But further we want to make RedSquare, BlackSquare shapes and GreenCircle, WhiteCircle shapes. In this case rather than creating one hierarchy of all the shapes, we separate the Color concern from Shape hierarchy. 

             So we create two hierarchies. One is Shape to Square and Shape to Circle hierarchy. Another one is Color to Red, Black, Green, White hierarchy. In this way we can create multiple types of shapes with multiple colors with Bridge design pattern.

23.Which is the design pattern used in Android applications?
                  Android applications predominantly use Model View Presenter design pattern.
1. Model: This is the domain model of the Android application. It contains the business logic and business rules. 
2. View: These are the UI components in your application. These are part of the view. Also any events on UI components are part of view module. 
3. Presenter: This is the bridge between Model and View to control the communication. Presenter can query the model and return data to view to update it. 
        E.g. If we have a Model with large news article data, and view needs only headline, then presenter can query the data from model and only give headline to view. In this way view remains very light in this design pattern.
24. How can we prevent users from creating more than one instance of singleton object by using clone() method?

                      First we should not implement the Cloneable interface by the object that is a Singleton. Second, if we have to implement Cloneable interface then we can throw exception in clone() method. This will ensure that no one can use clone() method or Cloneable interface to create more than one instance of Singleton object.




Basic Java       OOPs        Static       Inheritance  





Comments

Popular posts from this blog

Microservices Interview Questions

Microservices Interview Questions 1. What is a Microservice in Java? A Microservice is a small and autonomous piece of code that does one thing very well. It is focused on doing well one specific task in a big system. It is also an autonomous entity that can be designed, developed and deployed independently. Generally, it is implemented as a REST service on HTTP protocol, with technology-agnostic APIs. Ideally, it does not share database with any other service. 2. What are the benefits of Microservices architecture? Microservices provide many benefits. Some of the key benefits are: 1.      Scaling : Since there are multiple Microservices instead of one monolith, it is easier to scale up the service that is being used more. Eg. Let say, you have a Product Lookup service and Product Buy service. The frequency of Product Lookup is much higher than Product Buy service. In this case, you can just scale up the Product Lookup service to run on powerful hardware with multipl

DOCKER Interview questions

DOCKER 1. What is Docker? Docker is Open Source software. It provides the automation of Linux application deployment in a software container. We can do operating system level virtualization on Linux with Docker. Docker can package software in a complete file system that contains software code, runtime environment, system tools, & libraries that are required to install and run the software on a server. 2. What is the difference between Docker image and Docker container? Docker container is simply an instance of Docker image. A Docker image is an immutable file, which is a snapshot of container. We create an image with build command. When we use run command, an Image will produce a container. In programming language, an Image is a Class and a Container is an instance of the class. 3. How will you remove an image from Docker? We can use docker rmi command to delete an image from our local system. Exact command is: % docker rmi <Image Id> If we want to fin

Cloud Computing Interview Questions

Cloud Computing 1. What are the benefits of Cloud Computing? There are ten main benefits of Cloud Computing: Flexibility : The businesses that have fluctuating bandwidth demands need the flexibility of Cloud Computing. If you need high bandwidth, you can scale up your cloud capacity. When you do not need high bandwidth, you can just scale down. There is no need to be tied into an inflexible fixed capacity infrastructure. Disaster Recovery : Cloud Computing provides robust backup and recovery solutions that are hosted in cloud. Due to this there is no need to spend extra resources on homegrown disaster recovery. It also saves time in setting up disaster recovery. Automatic Software Updates : Most of the Cloud providers give automatic software updates. This reduces the extra task of installing new software version and always catching up with the latest software installs. Low Capital Expenditure : In Cloud computing the model is Pay as you Go. This means there is very