Java Design Patterns Interview Questions And Answers

Java Design Patterns Interview Questions And Answers for experienced professionals from Codingcompiler. These Java Design Patterns interview questions were asked in various interviews conducted by top multinational companies across the globe. We hope that these interview questions on Java Design Patterns will help you in cracking your job interview. All the best and happy learning.

  1. Java Design Patterns Interview Questions
  2. Frequently asked Java Design Patterns Interview Questions
  3. Advanced Java Design Patterns Interview Questions and Answers
  4. Top Java Design Patterns Interview Questions and answers
—-

Java Design Patterns Interview Questions

  1. What are Design Patterns?
  2. When to use Strategy Design Pattern in Java?
  3. Explain the advantages of Java design pattern?
  4. What is decorator pattern in Java? Can you give an example of Decorator pattern?
  5. Can you write thread-safe Singleton in Java?
  6. What are the Creational Patterns?
  7. Explain the Singleton pattern?
  8. Describe in how many ways can you create a singleton pattern?
  9. Is it possible to create a clone of a singleton object?
  10. How is Bridge pattern is different from the Adapter pattern?
—-

Java Design Patterns Interview Questions and answers

Q1. What are 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.

Q2. When to use Strategy Design Pattern in Java?

Java design pattern interview question and answers for senior and experience programmerStrategy pattern in quite useful for implementing set of related algorithms e.g. compression algorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes, which uses Strategy implementation classes for applying business rules. This pattern follows open closed design principle and quite useful in Java.

One of a good example of Strategy pattern from JDK itself is a Collections.sort() method and Comparator interface, which is a strategy interface and defines a strategy for comparing objects. Because of this pattern, we don’t need to modify sort() method (closed for modification) to compare any object, at the same time we can implement Comparator interface to define new comparing strategy (open for extension).

Q3. Explain the advantages of Java design pattern?

  • The Design Patterns are reusable in multiple projects.
  • The Design Patterns provide a solution that helps to define the system architecture.
  • The Design Patterns capture software engineering experiences.
  • The Design Patterns provide transparency to the design of an application.
  • They are testified and well-proved since they have been built upon the knowledge and experience of expert software developers.

Q4. What is decorator pattern in Java? Can you give an example of Decorator pattern?

Answer:

Decorator pattern is another popular Java design pattern question which is common because of its heavy usage in java.io package. BufferedReader and BufferedWriter are a good example of decorator pattern in Java. See How to use Decorator pattern in Java for more details.

Q5. Can you write thread-safe Singleton in Java?

Answer:

There are multiple ways to write thread-safe singleton in Java e.g by writing singleton using double checked locking, by using static Singleton instance initialized during class loading. By the way using Java enum to create thread-safe singleton is the most simple way. See Why Enum singleton is better in Java for more details.

Q6.  What are the Creational Patterns?

Answer:

Creational design patterns are related to the way of creating objects. Creational design patterns are used when a decision is made at the time of instantiation of a class.

EmpRecord e1=new EmpRecord();  

Since new keyword is used to create an object in Java, So, here we are creating the instance using the new keyword. In some cases, the nature of the object must be changed according to the nature of the program. In such cases, we should use the creational design patterns to provide a more general and flexible approach.

Q7. Explain the Singleton pattern?

Answer:

Singleton pattern in Java is a pattern which allows a single instance within an application. One good example of the singleton pattern is java.lang.Runtime.

Singleton Pattern states that define a class that has only one instance and provides a global point of access to it.

In other words, it is the responsibility of the class that only a single instance should be created, and all other classes can use a single object.

Q8. Describe in how many ways can you create a singleton pattern?

Answer:

There are two ways of creating a Singleton pattern.

1. Early Instantiation: It is responsible for the creation of instance at load time.

2. Lazy Instantiation: It is responsible for the creation of instance when required.

Q9.  Is it possible to create a clone of a singleton object?

Answer:

Yes, it is possible to create a clone of a singleton object.

Q10. How is Bridge pattern is different from the Adapter pattern?

Answer:

The motive of the Adapter pattern is to make interfaces of one or more classes to look similar.

The Bridge pattern is designed to isolate a class’s interface from its implementation so we can vary or substitute the implementation without changing the client code.

—-

Frequently asked Java Design Patterns Interview Questions

Q11. Name types of Design Patterns?

Answer:

Design patterns can be classified in three categories: Creational, Structural and Behavioral patterns.

Creational Patterns – These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator. This gives program more flexibility in deciding which objects need to be created for a given use case.

Structural Patterns – These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.

Behavioral Patterns – These design patterns are specifically concerned with communication between objects.

Q12. Design a Vending Machine which can accept different coins, deliver different products?

Answer:

This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question should be solve in 3 hours, at least a working version.

Q13. What is Bridge pattern?

Answer:

Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them.

This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.

Q14. What is Factory pattern?

Answer:

Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Q15. What is Abstract Factory pattern?

Answer:

Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

Q16. What is observer design pattern in Java?

Answer:

Observer design pattern is based on communicating changes in state of object to observers so that they can take there action. Simple example is a weather system where change in weather must be reflected in Views to show to public. Here weather object is Subject while different views are Observers. Look on this article for complete example of Observer pattern in Java.

Q17. What Are Advantages of Design Patterns?

Answer:

  • A design patterns are well-proved solution for solving the specific problem.
  • The benefit of design patterns lies in reusability and extensibility of the already developed applications.
  • Design patterns use object-oriented concepts like decomposition, inheritance and polymorphism.
  • They provide the solutions that help to define the system architecture.

Q18. If the singletons getInstance is not synchronized , how it would behave in multithreaded environment?

Answer: Threads can be unpredictable , we can’t guarantee when the method is unsynchronized it would give max of two singleton instance.

Q19. Can you write thread-safe Singleton in Java?

Answer:There are multiple ways to write thread-safe singleton in Java

By writing singleton using double checked locking.

By using static Singleton instance initialized during class loading.

By the way using Java enum to create thread-safe singleton this is most simple way.

Q20. How to implement a Singleton Java class?

Answer:

Given below is the most common way to construct a Singleton class. It works well in single threaded environment but has some drawback in multithreaded environment which will be explained as part of next question.

public class Singleton {

     //reference variable

     private static Singleton instance;

     /* prevent instantiation from outside 

        of class by making constructor private.*/

     private Singleton(){}

     /* if object exists, return the existing 

        object. If not, create and return a

        new object.*/

     public static Singleton getInstance() { 

        if (instance == null) {

         instance = new Singleton(); 

        }

        return instance; 

     }

     public void displayMessage(){

        System.out.println(“Java Hungry”);

     }

}

—-

Advanced Java Design Patterns Interview Questions and Answers

Q21. Which design pattern is preferred for creating a complex object?

Answer:

Builder design pattern is more suitable for creating complex object as it is an extension of Factory pattern and is created for solving the issues associated with Factory and Abstract Factory design patterns.

Q22. What is Prototype Design Pattern and when to use it?

Answer:

It is a creational design pattern which is used in cases when a large number of instances of a class are required and these instances are almost identical but may have slightly different properties. This pattern is useful in cases wherever there is high time and cost overhead associated with the object creation. This pattern mainly works by creating clone of the existing object instead of creating a new instance every time so that performance is optimized.

Q23. Which design pattern will you use to create a complex object?

Answer:

Builder design pattern is used to construct a complex object. It is designed to solve the issues with factory and abstract design pattern.

Q24. What is null Object Pattern?

Answer:

Null Object pattern is a design pattern in which null object replaces NULL check for instance variable. Instead of putting a check for a null value, Null Object reflects a do nothing relationship. It can also be used to provide default behavior in case data is not available.

Q25. Give an example of decorator design pattern?

Answer:

The decorator pattern, also known as a structural pattern is used to add additional functionality to a particular object at runtime. It wraps the original object through decorator object. For example, when you are buying a burger, you can customize it by adding extra filling and sauces, now the cost of these items have to be added to the final price. The customization will differ from customer to customer and offer from a shop. Creating different classes of burger with different fillings will end up creating a lot of classes. Decorator solves this problem by extending the functionality of single Burger class at runtime based on customer request.

Q26. Can you name few design patterns used in standard JDK library?

Answer:

1. Decorator design pattern which is used in various Java IO classes.

2. Singleton pattern which is used during runtime.

3. Calendar and various other classes.

4. Factory pattern which is used along with various Immutable classes like Boolean e.g. Boolean.valueOf.

5. Observer pattern which is used in Swing and many event listener frameworks.

Q27. When do you overload a method in Java and when do you override it ?

Answer:

Rather a simple question for experienced designer in Java. If one sees implementation of a class has different ways of doing certain things then overriding is the way to go while overloading is doing same thing but with different inputs. Method signature varies in case of overloading but not in case of overriding in java.

Q28. When to use the Template method?

Answer:

When the steps to solve an algorithm is fixed and if we can create a template of steps which subclass can implement based on their need, we can use template method design pattern.

In this pattern the template method itself should be final, so that subclass cannot override it and change the steps but if needed they can be made abstract so that the subclass can implement them based on the need.

Q29. Why would I ever use a Chain of Responsibility over a Decorator?

Answer: The key difference is that a Decorator adds new behaviour that in effect widens the original interface. It is similar to how normal extension can add methods except the “subclass” is only coupled by a reference which means that any “superclass” can be used.

The Chain of Responsibility pattern can modify an existing behaviour which is similar to overriding an existing method using inheritance. You can choose to call super.xxx() to continue up the “chain” or handle the message yourself.

Q30. . What benefits you achieve with factory method?

Answer. Factory method makes the code more flexible and reusable by eliminating the instantiation of application-specific classes. This way the code deals only with the interface and can work with any concrete class that supports this interface.

—-

Top Java Design Patterns Interview Questions and answers

Q31. Explain MVC design pattern in J2EE.

Answer:

MVC (Model-View-Controller) is a J2EE design pattern that decouples data access logic and presentation from business logic. MVC is a software architecture pattern for developing web application.

Model represents the application data domain. Application business logic is contained within the model and is responsible for maintaining data.

View It represents the user interface, with which the end users communicates and the model data is presented and viewed.

The Controller reacts to the user input. It creates, populates the model and helps identify the relevant view.

Q32. Explain Java beans pattern.

Answer:

Using JavaBeans pattern, you call a parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest as required.

private Person person1= new Person();

person1.setFirstName(“Steve”);

person1.setLastName(“Jobs”);

person1.setDescription(“Apple Founder”);

This is an alternative to the telescopic constructor pattern. Java beans pattern allows inconsistency and mandates mutability which is a drawback.

Q33. What is Transfer object design pattern in Java?

Answer:

Transfer object is a simple Java class with fields and contains no business logic. They are serializable POJO classes and have accessor methods (getter and setters) to access fields. These classes pass data between layers, they need not match business objects. Usually, Transfer objects group arguments to service method call.

Q34. What is proxy in Design pattern?

Answer:

Proxy generally means the in place of representing or on the behalf. Proxies are also known as the surrogate, handles and wrappers. The Proxy design is closely related to the structural design pattern.

Q35. What are Process Patterns? 

– Methods, best practices, techniques for developing an Object-Oriented software comprises a process pattern…

Q36. What are Collaboration Patterns?

Answr:  Repeatable techniques which are utilized by people of different teams for helping them work together…

Q37. What are Anti-Patterns? 

Answer:  A design pattern which obviously appears, but is an ineffective or far from optimal in practice.

Q38. How to prevent cloning of a singleton object?

Answer:

By Throwing exception within the body of clone method.

Q39. Difference between Service to Worker pattern and Dispatcher View pattern.

 Answer:

Both pattern use Front controller combined with Helpers with Dispatcher component.

In Service to worker, front controller delegates content retrieval to View Helpers. Controller also takes care of tasks like authentication, authorization etc.

In Dispatcher View, Controller does not delegate content retrieval to helpers. Most of the work is done by views.

Q40. What is Chain of Responsibility Design Pattern?

The Chain of Responsibility pattern is a behavior pattern in which a group of objects is chained together in a sequence and a responsibility (a request) is provided in order to be handled by the group. If an object in the group can process the particular request, it does so and returns the corresponding response. Otherwise, it forwards the request to the subsequent object in the group.

Related Interview Questions

  1. SAP HANA Interview Questions
  2. Core Java Interview Questions
  3. JSF Interview Questions
  4. JSP Interview Questions
  5. JPA Interview Questions
  6. Spring Framework Interview Questions
  7. Spring Boot Interview Questions
  8. Core Java Multiple Choice Questions
  9. 60 Java MCQ Questions And Answers
  10. Aricent Java Interview Questions
  11. Accenture Java Interview Questions
  12. Advanced Java Interview Questions For 5 8 10 Years Experienced
  13. Core Java Interview Questions For Experienced
  14. GIT Interview Questions And Answers
  15. Network Security Interview Questions
  16. CheckPoint Interview Questions
  17. Page Object Model Interview Questions
  18. Apache Pig Interview Questions
  19. Python Interview Questions And Answers
  20. Peoplesoft Integration Broker Interview Questions
  21. PeopleSoft Application Engine Interview Questions


Leave a Reply

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