YouTube Icon

Interview Questions.

Top 50 Java Design Patterns Interview Questions - Jul 26, 2022

fluid

Top 50 Java Design Patterns Interview Questions

Q1. Define A Factory With Respect To Software Development?

Object production is referred as a factory.

It is used to isolate the introduction of items from their usage.

If you're the use of manufacturing facility methods for items creation, then the brand new derived kinds will reason no code exchange to your training which can be using factories.

Q2. What Is Abstract Factory Pattern?

Abstract Factory styles work around a awesome-manufacturing facility which creates other factories.

This manufacturing facility isalso known as as manufacturing facility of factories.

This kind of design sample comes below creational sample asthis pattern provides one of the nice approaches to create an item.

In Abstract Factory pattern an interface is answerable for developing a manufacturing facility of associated items with out explicitly specifying their instructions.

Each generated factory can provide the items as in step with the Factory pattern.

Q3. What Is Composite Entity Pattern?

Composite Entity pattern is used in EJB staying power mechanism :

A Composite entity is an EJB entity bean which represents a graph of objects.

When a composite entity is updated, internally dependent objects be get updated automatically as being managed by way of EJB entity bean.

Following are the individuals in Composite Entity Bean:

Composite Entity - It is number one entity bean. It may be coarse grained or can include a rough grained item for use for endurance motive.

Coarse-Grained Object - This object consists of based objects. It has its very own lifestyles cycle and also manages lifestyles cycle of structured items.

Dependent Object - Dependent item is an item which depends on coarse grained object for its persistence lifecycle.

Strategies - Strategies represents how to enforce a Composite Entity.

Q4. What Is Command Pattern?

Command sample is a data pushed layout sample and falls beneath behavioral sample category.

A request is wrapped below an object as command and passed to invoker object.

Invoker object looks for the appropriate item that may deal with this command and passes the command to the corresponding object which executes the command.

Q5. What Is Interpreter Pattern?

Interpreter sample affords a way to evaluate language grammar or expression.

This sort of pattern comes beneath behavioral pattern.

This pattern entails imposing an expression interface which tells to interpret a particular context.

Q6. What Is Intercepting Filter Pattern?

The intercepting filter out layout pattern is used whilst we need to do a little pre-processing / postprocessing with request or response of the application:

Filters are described and implemented at the request earlier than passing the request to real goal application.

Filters can do the authentication/ authorization/ logging or monitoring of request and then bypass the requests to corresponding handlers.

Q7. What Is Factory Pattern?

Factory sample is considered one of maximum used layout sample in Java.

Thistype of design pattern comesunder creational sample as this sample affords one of the excellent methods to create an item.

In Factory sample, we create object with out exposing the creation common sense to the client and refer tonewly created item using a common interface.

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

This layout pattern query is requested on Java interview not simply to test familiarity with Composite pattern however additionally, whether or not candidate has actual lifestyles enjoy or now not.

Composite sample is also a core Java design pattern, which lets in you to treat each whole and element item to deal with in comparable way.

Client code, which deals with Composite or character object does not differentiate on them, it's miles feasible due to the fact Composite magnificence also enforce same interface as there man or woman element.

One of the coolest example of Composite sample from JDK is JPanel class, that is both Component and Container.

When paint() technique is referred to as on JPanel, it internally known as paint() method of man or woman components and allow them to draw themselves.

On 2d a part of this design pattern interview question, be truthful, when you have used then say yes, otherwise say which you are acquainted with concept and used it via your personal.

By the manner continually recollect, giving an example from your mission creates better impact.

Q9. What Is State Pattern?

In State pattern a category behavior modifications based totally on its nation.

This sort of layout pattern comes below conduct sample.

In State pattern, we create gadgets which represent numerous states and a context item whose conduct varies as its nation item adjustments.

Q10. What Is Business Delegate Pattern?

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

It is basically use to reduce communique or faraway lookup capability to enterprise tier code in presentation tier code.

In enterprise tier we have following entities:

Client - Presentation tier code can be JSP, servlet or UI java code.

Business Delegate - A unmarried access factor class for purchaser entities to provide access to Business Service strategies.

LookUp Service - Lookup service object is responsible to get relative enterprise implementation and provide enterprise object get admission to to commercial enterprise delegate item.

Business Service - Business Service interface. Concrete lessons put into effect this commercial enterprise provider to provide actual enterprise implementation logic.

Q11. Name The Actor Classes Used In Memento Pattern?

Memento pattern uses 3 actor training.

Memento contains nation of an object to be restored.

Originator creates and shops states in Memento gadgets and Caretaker item is responsible to restore item nation from Memento.

Q12. What Is Prototype Pattern?

Prototype sample refers to developing reproduction object while retaining overall performance in mind.

This sample involves enforcing a prototype interface which tells to create a the image of the modern object.

Q13. What Are The Entities Of Service Locator Pattern?

Following are the entities of this kind of design sample:

Service - Actual Service so that you can system the request. Reference of such provider is to be seemed upon in JNDI server.

Context / Initial Context - JNDI Context consists of the connection with service used for research cause.

Service Locator - Service Locator is a single factor of touch to get offerings with the aid of JNDI research caching the services.

Cache - Cache to save references of services to reuse them.

Client - Client is the item that invokes the services via ServiceLocator.

Q14. What Is Facade Pattern?

Facade sample hides the complexities of the device and presents an interface to the purchaser using which the consumer can get right of entry to the system.

This type of layout sample comes below structural sample as this pattern adds an interface to existing machine to cover its complexities.

This sample involves a single elegance which offers simplified strategies required by customer and delegates calls to strategies of present system instructions.

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

Following are the variations between a static magnificence and a singleton elegance:

A static magnificence can not be a pinnacle stage class and cannot implement interfaces wherein a singleton magnificence can.

All members of a static class are static but for a Singleton magnificence it is not a demand.

A static magnificence get initialized while it's miles loaded so it can't be lazily loaded in which a singleton class can be lazily loaded.

A static magnificence item is stored in stack while singlton magnificence item is stored in heap memory space.

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

Decorator sample complements functionality of individual object.

Java IO uses decorator pattern notably and classical example is Buffered training like BufferedReader and BufferedWriter which complements Reader and Writer gadgets to perform Buffer stage reading and writing for progressed performance.

Q17. Can You Write Thread-secure Singleton In Java?

There are more than one methods to write down thread-safe singleton in Java e.G by means of writing singleton using double checked locking, through the usage of static Singleton instance initialized during magnificence loading. By the way the usage of Java enum to create thread-safe singleton is most simple manner.

Q18. How Can You Create Singleton Class In Java?

It is  step technique:

First, make the constructor private so that new operator can't be used to instantiate the elegance.

Return an item of the object if not null in any other case create the object and go back the identical via a method.

Q19. What Is Data Access Object Patterndao Pattern?

Data Access Object Pattern or DAO pattern is used to split low degree facts accessing API or operations from high degree commercial enterprise offerings.

Following are the individuals in Data Access Object Pattern:

Data Access Object Interface - This interface defines the same old operations to be completed on a model items.

Data Access Object concrete class - This class implements above interface. This elegance is accountable to get information from a records supply which may be database / xml or any other storage mechanism.

Model Object or Value Object - This object is straightforward POJO containing get/set methods to keep facts retrieved using DAO elegance.

Q20. What Is Composite Pattern?

Composite sample is used where we need to deal with a collection of items in comparable way as a unmarried item.

Composite pattern composes gadgets in time period of a tree shape to symbolize element in addition to complete hierarchy.

This kind of design pattern comes below structural sample as this sample creates a tree shape of organization of objects.

This pattern creates a category that consists of organization of its very own gadgets.

This elegance gives ways to adjust its institution of same objects.

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

Observer sample is primarily based upon notification, there are  sorts of object Subject and Observer.Whenever there is exchange on concern's nation observer will obtain notification.

Q22. Can We Create A Clone Of A Singleton Object?

Yes.

Q23. What Is Proxy Pattern?

In proxy pattern, a category represents functionality of another class.

This form of design sample comes under structural sample.

In proxy sample, we create item having original object to interface its functionality to outer world.

Q24. What Is Strategy Pattern?

In Strategy pattern, a class behavior or its set of rules can be modified at run time.

This form of layout pattern comes below behavior sample.

In Strategy sample, we create objects which constitute diverse strategies and a context object whose behavior varies as in step with its strategy item.

The approach item changes the executing set of rules of the context object.

Q25. What Is Builder Pattern?

Builder sample builds a complicated object the use of easy items and the use of a step by step method.

This builder is unbiased of different objects.

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

Using new operator to create objects is a legitimate technique but it's like tough coding the object kind.

If we're one hundred% sure that our item could be of the equal elegance all the time, then we use new operator to create an object.

In situations wherein the nature of the object can trade in keeping with the nature of the program, we use creational layout patterns which provide bendy approach for growing elegance times.

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

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

Q28. When Prototype Pattern Is To Be Used?

This sample is used whilst creation of item at once is highly-priced.

For instance, an object is to be created after a pricey database operation.

We can cache the object, returns its clone on subsequent request and replace the database as and whilst needed as a consequence reducing database calls.

Q29. What Is Iterator Pattern?

Iterator pattern may be very typically used layout sample in Java and.Net programming environment.

This sample is used to get a manner to get admission to the factors of a collection item in sequential way without any need to recognize its underlying illustration.

Iterator sample falls beneath behavioral pattern category.

Q30. What Is Decorator Pattern?

Decorator pattern allows a consumer to feature new capability to an present item without changing its structure.

This form of design sample comes under structural pattern as this pattern acts as a wrapper to current magnificence.

This sample creates a decorator magnificence which wraps the authentic class and affords additional capability maintaining elegance methods signature intact.

Q31. What Is Template Pattern?

In Template pattern, an summary class exposes described approaches/templates to execute its techniques.

Its subclasses can override the approach implementation as in keeping with want however the invocation is to be within the equal way as described with the aid of an abstract elegance.

This pattern comes under conduct sample category.

Q32. What Is Mvc Pattern?

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

Model - Model represents an object or JAVA POJO sporting statistics. It can also have good judgment to update controller if its facts changes.

View - View represents the visualization of the records that version incorporates.

Controller - Controller acts on each model and think about. It controls the facts circulate model item and updates the view every time records changes. It continues view and version separate.

Q33. What Is Service Locator Pattern?

The carrier locator design pattern is used while we want to locate numerous offerings the use of JNDI lookup:

Considering high cost of looking up JNDI for a carrier, Service Locator sample uses caching technique.

For the first time a service is required, Service Locator seems up in JNDI and caches the provider object.

Further lookup or same carrier via Service Locator is completed in its cache which improves the performance of software to great volume.

Q34. What Is Singleton Pattern?

Singleton pattern is one of the most effective layout patterns in Java.

This form of layout sample comesunder creational pattern as this sample provides one of the first-class methods to create an item.

This sample involves a single class that is responsible to create an item even as ensuring that simplest unmarried object receives created.

This magnificence offers a manner to access its only item which may be accessed without delay without want to instantiate the item of the elegance.

Q35. What Is Flyweight Pattern?

Flyweight sample is often used to lessen the number of gadgets created and to lower reminiscence footprint and boom performance.

This sort of design sample comes underneath structural pattern as this pattern presents methods to lower item be counted for this reason enhancing the object shape of utility.

Flyweight sample tries to reuse already existing comparable type items by using storing them and creates new object when no matching object is located.

Q36. What Are Design Patterns?

Design styles represent the pleasant practices used by experienced object-orientated software program builders.

Design styles are solutions to standard troubles that software program developers confronted throughout software program development.

These solutions have been received by means of trial and error with the aid of severa software builders over quite a massive period of time.

Q37. What Is Gang Of Four Gof?

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

These authors are together called Gang of Four GOF.

Q38. What Is Adapter Pattern?

Adapter sample works as a bridge between  incompatible interfaces.

This pattern involves a single elegance that's responsible to join functionalities of independent or incompatible interfaces.

An example of Adapter sample:

A actual lifestyles instance will be a case of card reader which acts as an adapter among memory card and a computer.

You plugin the memory card into card reader and card reader into the computer so that memory card may be study through computer.

Q39. How To Prevent Cloning Of A Singleton Object?

Throw exception within the body of clone technique.

Q40. What Are The Entities Of Intercepting Filter Pattern?

Following are the entities of this kind of design pattern:

Filter - Filter as a way to plays certain mission previous or after execution of request with the aid of request handler.

Filter Chain - Filter Chain consists of a couple of filters and assist to execute them in defined order on course.

Target - Target item is the request handler.

Filter Manager - Filter Manager manages the filters and Filter Chain.

Client - Client is the item who sends request to the Target item.

Q41. Define Creational Design Patterns?

Creational styles are used to outline and describe how items are created at magnificence instantiation time.

Usually an summary excellent elegance carries the info of the instructions which are instantiated and the patron elegance is ignorant of such details.

Singletion pattern, manufacturing unit technique pattern, abstract manufacturing facility sample are examples of creational design sample.

Q42. What Are J2ee Patterns?

These layout patterns are specifically worried with the presentation tier.

These styles are identified by way of Sun Java Center.

Q43. What Is Front Controller Pattern?

The the front controller design pattern is used to provide a centralized request managing mechanism so that all requests can be handled via a unmarried handler.

This handler can do the authentication/ authorization/ logging or monitoring of request after which pass the requests to corresponding handlers.

Following are the entities of this type of design pattern:

Front Controller - Single handler for all sorts of requests coming to the software eitherwebbased/desktopbased.

Dispatcher - Front Controller may additionally use a dispatcher item that could dispatch the request to corresponding precise handler.

View - Views are the item for which the requests are made.

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

Factory pattern used to create item by using supplying static manufacturing facility strategies. There are many advantage of offering factory techniques e.G. Caching immutable items, smooth to introduce new objects and many others.

Q45. Name Types Of Design Patterns?

Design styles can be labeled in 3 classes:

Creational styles

Structural patterns

Behavioral patterns

Creational Patterns - These layout patterns provide a manner to create objects even as hiding the creation common sense, in preference to instantiating items immediately the use of new opreator. This offers software greater flexibility in identifying which gadgets want to be created for a given use case.

Structural Patterns - These design patterns difficulty elegance and object composition. Concept of inheritance is used to compose interfaces and define ways to compose gadgets to attain new functionalities.

Behavioral Patterns - These layout styles are in particular concerned with communication between objects.

Q46. What Is Singleton Pattern In Java?

Singleton pattern in Java is a sample which allows most effective one instance of Singleton class to be had in whole application.

Q47. What Is Observer Design Pattern In Java?

Observer layout pattern is based on communicating adjustments in country of item to observers with a purpose to take there movement.

Simple instance is a climate gadget wherein change in climate have to be reflected in Views to reveal to public.

Here climate item is Subject at the same time as exclusive perspectives are Observers.

Look on this article for entire instance of Observer sample in Java.

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

Following are some of the layout patterns which are utilized in JDK library:

Decorator patttern is utilized by Wrapper classes.

Singleton pattern is used by Runtime, Calendar training.

Factory pattern is used by Wrapper magnificence like Integer.ValueOf.

Observer pattern is utilized by event coping with frameworks like swing, awt.

Q49. What Is The Benefit Of Factory Pattern?

Factory pattern encapsulates the implementation details and underlying implementation can be modified with none impact on caller api.

Q50. What Is Mediator Pattern?

Mediator sample is used to lessen conversation complexity among multiple gadgets or lessons.

This sample presents a mediator magnificence which generally handles all the communications between special training and helps smooth upkeep of the code by way of loose coupling.

Mediator pattern falls beneath behavioral sample category.




CFG