Java Design Patterns Interview Questions & Answers

Java Design Patterns Interview Questions

If you are a Java Expert then this is for you. Let us know if you looking for a job change? Are you prepared in attending an interview? Then do not worry, we’ve a right answer for your job interview preparation. If you are preparing for Java Design Patterns job interview and don’t know how to crack interview and what level or difficulty of questions to be asked in job interviews then go through Wisdomjobs interview questions and answers page to crack your job interview. A design pattern is a general repeatable solution to a commonly occurring problem in software design. Below are the frequently asked Java Design Patterns interview questions and answers which makes you comfortable to face the interviews:

Java Design Patterns Interview Questions And Answers

Java Design Patterns Interview Questions
    1. Question 1. What Are Design Patterns?

      Answer :

      • 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.

    2. Question 2. What Is Gang Of Four Gof?

      Answer :

      In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development.

      These authors are collectively known as Gang of Four GOF.

    3. Question 3. Name Types Of Design Patterns?

      Answer :

      Design patterns can be classified in three categories:

      • Creational patterns
      • Structural patterns
      • 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.

    4. Question 4. What Are J2ee Patterns?

      Answer :

      • These design patterns are specifically concerned with the presentation tier.
      • These patterns are identified by Sun Java Center.

    5. Question 5. What Is Factory Pattern?

      Answer :

      • Factory pattern is one of most used design pattern in Java.
      • Thistype of design pattern comesunder 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 tonewly created object using a common interface.

    6. Question 6. What Is Abstract Factory Pattern?

      Answer :

      • Abstract Factory patterns work around a super-factory which creates other factories.
      • This factory isalso called as factory of factories.
      • This type of design pattern comes under creational pattern asthis 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.

    7. Question 7. What Is Singleton Pattern?

      Answer :

      • Singleton pattern is one of the simplest design patterns in Java.
      • This type of design pattern comesunder creational pattern as this pattern provides one of the best ways to create an object.
      • This pattern involves a single class which is responsible to create an object while making sure that only single object gets created.
      • This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

    8. Question 8. How Can You Create Singleton Class In Java?

      Answer :

      It is two step process:

      • First, make the constructor private so that new operator cannot be used to instantiate the class.
      • Return an object of the object if not null otherwise create the object and return the same via a method.

    9. Question 9. What Are The Difference Between A Static Class And A Singleton Class?

      Answer :

      Following are the differences between a static class and a singleton class:

      • A static class can not be a top level class and can not implement interfaces where a singleton class can.
      • All members of a static class are static but for a Singleton class it is not a requirement.
      • A static class get initialized when it is loaded so it can not be lazily loaded where a singleton class can be lazily loaded.
      • A static class object is stored in stack whereas singlton class object is stored in heap memory space.

    10. Question 10. Can We Create A Clone Of A Singleton Object?

      Answer :


    11. Question 11. How To Prevent Cloning Of A Singleton Object?

      Answer :

      Throw exception within the body of clone method.

    12. Question 12. Name Some Of The Design Patterns Which Are Used In Jdk Library?

      Answer :

      Following are some of the design patterns which are used in JDK library:

      • Decorator patttern is used by Wrapper classes.
      • Singleton pattern is used by Runtime, Calendar classes.
      • Factory pattern is used by Wrapper class like Integer.valueOf.
      • Observer pattern is used by event handling frameworks like swing, awt.

    13. Question 13. What Is The Benefit Of Factory Pattern?

      Answer :

      Factory pattern encapsulates the implementation details and underlying implementation can be changed without any impact on caller api.

    14. Question 14. What Is Builder Pattern?

      Answer :

      • Builder pattern builds a complex object using simple objects and using a step by step approach.
      • This builder is independent of other objects.

    15. Question 15. What Is Prototype Pattern?

      Answer :

      • Prototype pattern refers to creating duplicate object while keeping performance in mind.
      • This pattern involves implementing a prototype interface which tells to create a clone of the current object.

    16. Question 16. When Prototype Pattern Is To Be Used?

      Answer :

      • This pattern is used when creation of object directly is costly.
      • For example, an object is to be created after a costly database operation.
      • We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

    17. Question 17. What Is Adapter Pattern?

      Answer :

      • Adapter pattern works as a bridge between two incompatible interfaces.
      • This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces.

      An example of Adapter pattern:

      • A real life example could be a case of card reader which acts as an adapter between memory card and a laptop.
      • You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

    18. Question 18. 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.

    19. Question 19. What Is Filter Pattern?

      Answer :

      Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and chaining them in a decoupled way through logical operations.

      This type of design pattern comes under structural pattern as this pattern combines multiple criteria to obtain single criteria.

    20. Question 20. What Is Composite Pattern?

      Answer :

      • Composite pattern is used where we need to treat a group of objects in similar way as a single object.
      • Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy.
      • This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects.
      • This pattern creates a class that contains group of its own objects.
      • This class provides ways to modify its group of same objects.

    21. Question 21. What Is Decorator Pattern?

      Answer :

      • Decorator pattern allows a user to add new functionality to an existing object without altering its structure.
      • This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.
      • This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.

    22. Question 22. What Is Facade Pattern?

      Answer :

      • Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.
      • This type of design pattern comes under structural pattern as this pattern adds an interface to existing system to hide its complexities.
      • This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes.

    23. Question 23. What Is Flyweight Pattern?

      Answer :

      • Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance.
      • This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application.
      • Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object when no matching object is found.

    24. Question 24. What Is Proxy Pattern?

      Answer :

      • In proxy pattern, a class represents functionality of another class.
      • This type of design pattern comes under structural pattern.
      • In proxy pattern, we create object having original object to interface its functionality to outer world.

    25. Question 25. What Is Chain Of Responsibility Pattern?

      Answer :

      • As the name suggests, the chain of responsibility pattern creates a chain of receiver objects for arequest.
      • This pattern decouples sender and receiver of a request based on type of request.
      • This pattern comes under behavioral patterns.
      • In this pattern, normally each receiver contains reference to another receiver.
      • If one object cannot handle the request then it passes the same to the next receiver and so on.

    26. Question 26. What Is Command Pattern?

      Answer :

      • Command pattern is a data driven design pattern and falls under behavioral pattern category.
      • A request is wrapped under an object as command and passed to invoker object.
      • Invoker object looks for the appropriate object which can handle this command and passes the command to the corresponding object which executes the command.

    27. Question 27. What Is Interpreter Pattern?

      Answer :

      • Interpreter pattern provides a way to evaluate language grammar or expression.
      • This type of pattern comes under behavioral pattern.
      • This pattern involves implementing an expression interface which tells to interpret a particular context.

    28. Question 28. Give An Example Where Interpreter Pattern Is Used?

      Answer :

      This pattern is used in SQL parsing, symbol processing engine etc.

    29. Question 29. What Is Iterator Pattern?

      Answer :

      • Iterator pattern is very commonly used design pattern in Java and.Net programming environment.
      • This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation.
      • Iterator pattern falls under behavioral pattern category.

    30. Question 30. What Are The Entities Of Service Locator Pattern?

      Answer :

      Following are the entities of this type of design pattern:

      • Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server.
      • Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose.
      • Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services.
      • Cache - Cache to store references of services to reuse them.
      • Client - Client is the object that invokes the services via ServiceLocator.

    31. Question 31. What Is Mediator Pattern?

      Answer :

      • Mediator pattern is used to reduce communication complexity between multiple objects or classes.
      • This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling.
      • Mediator pattern falls under behavioral pattern category.

    32. Question 32. What Is Memento Pattern?

      Answer :

      • Memento pattern is used to restore state of an object to a previous state.
      • Memento pattern falls under behavioral pattern category.

    33. Question 33. Name The Actor Classes Used In Memento Pattern?

      Answer :

      • Memento pattern uses three actor classes.
      • Memento contains state of an object to be restored.
      • Originator creates and stores states in Memento objects and Caretaker object is responsible to restore object state from Memento.

    34. Question 34. What Is Observer Pattern?

      Answer :

      • Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically.
      • Observer pattern falls under behavioral pattern category.

    35. Question 35. Name The Actor Classes Used In Observer Pattern?

      Answer :

      • Observer pattern uses three actor classes. Subject, Observer and Client.
      • Subject is an object having methods to attach and detach observers to a client object.
      • We have created an abstract class Observer and a concrete class Subject that is extending class Observer.

    36. Question 36. What Is State Pattern?

      Answer :

      • In State pattern a class behavior changes based on its state.
      • This type of design pattern comes under behavior pattern.
      • In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

    37. Question 37. What Is Null Object Pattern?

      Answer :

      • In Null Object pattern, a null object replaces check of NULL object instance.
      • Instead of putting if check for a null value, Null Object reflects a do nothing relationship.
      • Such Null object can also be used to provide default behaviour in case data is not available.
      • In Null Object pattern, we create an abstract class specifying various operations to be done, concrete classes extending this class and a null object class providing do nothing implemention of this class and will be used seemlessly where we need to check null value.

    38. Question 38. What Is Strategy Pattern?

      Answer :

      • In Strategy pattern, a class behavior or its algorithm can be changed at run time.
      • This type of design pattern comes under behavior pattern.
      • In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.
      • The strategy object changes the executing algorithm of the context object.

    39. Question 39. What Is Template Pattern?

      Answer :

      • In Template pattern, an abstract class exposes defined ways/templates to execute its methods.
      • Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class.
      • This pattern comes under behavior pattern category.

    40. Question 40. What Is Visitor Pattern?

      Answer :

      • In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class.
      • By this way, execution algorithm of element can vary as and when visitor varies.
      • This pattern comes under behavior pattern category.
      • As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the element object.

    41. Question 41. What Is Mvc Pattern?

      Answer :

      MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns. 

      • Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
      • View - View represents the visualization of the data that model contains.
      • Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.

    42. Question 42. What Is Business Delegate Pattern?

      Answer :

      Business Delegate Pattern is used to decouple presentation tier and business tier:

      It is basically use to reduce communication or remote lookup functionality to business tier code in presentation tier code.

      In business tier we have following entities:

      • Client - Presentation tier code may be JSP, servlet or UI java code.
      • Business Delegate - A single entry point class for client entities to provide access to Business Service methods.
      • LookUp Service - Lookup service object is responsible to get relative business implementation and provide business object access to business delegate object.
      • Business Service - Business Service interface. Concrete classes implement this business service to provide actual business implementation logic.

    43. Question 43. What Is Composite Entity Pattern?

      Answer :

      Composite Entity pattern is used in EJB persistence mechanism :

      • A Composite entity is an EJB entity bean which represents a graph of objects.
      • When a composite entity is updated, internally dependent objects beans get updated automatically as being managed by EJB entity bean.

      Following are the participants in Composite Entity Bean:

      • Composite Entity - It is primary entity bean. It can be coarse grained or can contain a coarse grained object to be used for persistence purpose.
      • Coarse-Grained Object - This object contains dependent objects. It has its own life cycle and also manages life cycle of dependent objects.
      • Dependent Object - Dependent object is an object which depends on coarse grained object for its persistence lifecycle.
      • Strategies - Strategies represents how to implement a Composite Entity.

    44. Question 44. What Is Data Access Object Patterndao Pattern?

      Answer :

      Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services.

      Following are the participants in Data Access Object Pattern:

      • Data Access Object Interface - This interface defines the standard operations to be performed on a model objects.
      • Data Access Object concrete class - This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism.
      • Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

    45. Question 45. What Is Front Controller Pattern?

      Answer :

      The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler.

      This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers.

      Following are the entities of this type of design pattern:

      • Front Controller - Single handler for all kinds of requests coming to the application eitherwebbased/desktopbased.
      • Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler.
      • View - Views are the object for which the requests are made.

    46. Question 46. What Is Intercepting Filter Pattern?

      Answer :

      The intercepting filter design pattern is used when we want to do some pre-processing / postprocessing with request or response of the application:

      • Filters are defined and applied on the request before passing the request to actual target application.
      • Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers.

    47. Question 47. What Are The Entities Of Intercepting Filter Pattern?

      Answer :

      Following are the entities of this type of design pattern:

      • Filter - Filter which will performs certain task prior or after execution of request by request handler.
      • Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target.
      • Target - Target object is the request handler.
      • Filter Manager - Filter Manager manages the filters and Filter Chain.
      • Client - Client is the object who sends request to the Target object.

    48. Question 48. What Is Service Locator Pattern?

      Answer :

      The service locator design pattern is used when we want to locate various services using JNDI lookup:

      • Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique.
      • For the first time a service is required, Service Locator looks up in JNDI and caches the service object.
      • Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent.

    49. Question 49. 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.

    50. Question 50. Give Example Of Decorator Design Pattern In Java ? Does It Operate On Object Level Or Class Level?

      Answer :

      • Decorator pattern enhances capability of individual object.
      • Java IO uses decorator pattern extensively and classical example is Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading and writing for improved performance.

    51. Question 51. Define Creational Design Patterns?

      Answer :

      • Creational patterns are used to define and describe how objects are created at class instantiation time.
      • Usually an abstract super class contains the details of the classes that are instantiated and the client class is unaware of such details.
      • Singletion pattern, factory method pattern, abstract factory pattern are examples of creational design pattern.

    52. Question 52. A Class Instance Can Be Created Using New Operator. Why Should We Use Creational Design Patterns To Create Objects?

      Answer :

      • Using new operator to create objects is a valid approach but it's like hard coding the object type.
      • If we are 100% sure that our object will be of the same class all the time, then we use new operator to create an object.
      • In scenarios where the nature of the object can change according to the nature of the program, we use creational design patterns which offer flexible approach for creating class instances.

    53. Question 53. Which Object Oriented Method Is Used By The Creational Patterns To Instantiate Object?

      Answer :

      Creational patterns use inheritance to decide the object to be instantiated.

    54. Question 54. Define A Factory With Respect To Software Development?

      Answer :

      • Object construction is referred as a factory.
      • It is used to isolate the creation of objects from their usage.
      • If you are using factory methods for objects creation, then the new derived types will cause no code change in your classes that are using factories.

    55. Question 55. When Will You Use A Factory Pattern?

      Answer :

      The factory pattern is preferred in the following cases: - a class does not know which class of objects it must create - factory pattern can be used where we need to create an object of any one of sub-classes depending on the data provided

    56. Question 56. When To Use Composite Design Pattern In Java? Have You Used Previously In Your Project?

      Answer :

      • This design pattern question is asked on Java interview not just to check familiarity with Composite pattern but also, whether candidate has real life experience or not.
      • Composite pattern is also a core Java design pattern, which allows you to treat both whole and part object to treat in similar way.
      • Client code, which deals with Composite or individual object doesn't differentiate on them, it is possible because Composite class also implement same interface as there individual part.
      • One of the good example of Composite pattern from JDK is JPanel class, which is both Component and Container.
      • When paint() method is called on JPanel, it internally called paint() method of individual components and let them draw themselves.
      • On second part of this design pattern interview question, be truthful, if you have used then say yes, otherwise say that you are familiar with concept and used it by your own.
      • By the way always remember, giving an example from your project creates better impression.

    57. Question 57. What Is Singleton Pattern In Java?

      Answer :

      Singleton pattern in Java is a pattern which allows only one instance of Singleton class available in whole application.

    58. Question 58. 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 most simple way.

    59. Question 59. What Is Factory Pattern In Java? What Is Advantage Of Using Static Factory Method To Create Object?

      Answer :

      Factory pattern used to create object by providing static factory methods. There are many advantage of providing factory methods e.g. caching immutable objects, easy to introduce new objects etc.

    60. Question 60. What Is Observer Design Pattern In Java? When Do You Use Observer Pattern In Java?

      Answer :

      Observer pattern is based upon notification, there are two kinds of object Subject and Observer.Whenever there is change on subject's state observer will receive notification.

Popular Interview Questions

All Interview Questions

Java Design Patterns Practice Test

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Tutorial