Interview Questions.

Top 100+ Java Design Patterns Interview Questions And Answers

fluid

Top 100+ Java Design Patterns Interview Questions And Answers

Question 1. What Are Design Patterns?

Answer :

Design styles represent the first-rate practices used by skilled object-oriented software developers.
Design styles are solutions to trendy troubles that software program builders faced at some stage in software program development.
These answers have been received by means of trial and blunders by using numerous software program builders over quite a giant time period.
Question 2. What Is Gang Of Four Gof?

Answer :

In 1994, 4 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 improvement.

These authors are together called Gang of Four GOF.

Adv Java Interview Questions
Question three. Name Types Of Design Patterns?

Answer :

Design patterns may be categorised in three categories:

Creational patterns
Structural patterns
Behavioral patterns
Creational Patterns - These layout patterns offer a manner to create objects while hiding the advent logic, in preference to instantiating items without delay the usage of new opreator. This offers application more flexibility in determining which objects need to be created for a given use case.
Structural Patterns - These layout patterns concern class and item composition. Concept of inheritance is used to compose interfaces and define ways to compose gadgets to gain new functionalities.
Behavioral Patterns - These layout patterns are especially worried with conversation between objects.

Question four. What Are J2ee Patterns?

Answer :

These design patterns are specially worried with the presentation tier.
These styles are identified by using Sun Java Center.
Adv Java Tutorial
Question five. What Is Factory Pattern?

Answer :

Factory pattern is one among most used layout pattern in Java.
Thistype of layout sample comesunder creational sample as this pattern presents one of the exceptional methods to create an item.
In Factory sample, we create object with out exposing the advent logic to the consumer and refer tonewly created object the usage of a commonplace interface.
J2EE Interview Questions
Question 6. What Is Abstract Factory Pattern?

Answer :

Abstract Factory styles paintings around a super-manufacturing facility which creates other factories.
This factory isalso known as as manufacturing unit of factories.
This type of layout pattern comes below creational pattern asthis pattern presents one of the first-rate methods to create an object.
In Abstract Factory sample an interface is liable for growing a manufacturing facility of associated gadgets with out explicitly specifying their classes.
Each generated factory can provide the objects as in step with the Factory pattern.
Question 7. What Is Singleton Pattern?

Answer :

Singleton sample is one of the simplest design styles in Java.
This kind of layout sample comesunder creational sample as this sample gives one of the first-class methods to create an item.
This sample involves a single elegance that is responsible to create an item whilst ensuring that handiest single item gets created.
This magnificence offers a manner to get entry to its simplest item which may be accessed directly without need to instantiate the object of the class.
J2EE Tutorial Core Java Interview Questions
Question eight. How Can You Create Singleton Class In Java?

Answer :

It is two step process:

First, make the constructor private in order that new operator can not be used to instantiate the elegance.
Return an object of the object if no longer null otherwise create the item and return the same thru a way.
Question nine. What Are The Difference Between A Static Class And A Singleton Class?

Answer :

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

A static magnificence cannot be a pinnacle stage magnificence and can not enforce interfaces in which a singleton elegance can.
All members of a static elegance are static but for a Singleton elegance it is not a requirement.
A static class get initialized while it's miles loaded so it cannot be lazily loaded where a singleton class can be lazily loaded.
A static class object is stored in stack whereas singlton class object is saved in heap reminiscence space.
JSP Interview Questions
Question 10. Can We Create A Clone Of A Singleton Object?

Answer :

Yes.

Core Java Tutorial
Question eleven. How To Prevent Cloning Of A Singleton Object?

Answer :

Throw exception within the body of clone technique.

Java-Springs Interview Questions
Question 12. Name Some Of The Design Patterns Which Are Used In Jdk Library?

Answer :

Following are a number of the design styles that are used in JDK library:

Decorator patttern is used by Wrapper classes.
Singleton sample is utilized by Runtime, Calendar training.
Factory pattern is used by Wrapper elegance like Integer.ValueOf.
Observer sample is utilized by event dealing with frameworks like swing, awt.
Adv Java Interview Questions
Question thirteen. What Is The Benefit Of Factory Pattern?

Answer :

Factory sample encapsulates the implementation information and underlying implementation can be changed without any effect on caller api.

JSP Tutorial
Question 14. What Is Builder Pattern?

Answer :

Builder sample builds a complex object the usage of simple items and the usage of a little by little method.
This builder is independent of different items.
Question 15. What Is Prototype Pattern?

Answer :

Prototype sample refers to creating replica object even as retaining performance in thoughts.
This pattern entails imposing a prototype interface which tells to create a the image of the cutting-edge item.
JMS(Java Message Service) Interview Questions
Question 16. When Prototype Pattern Is To Be Used?

Answer :

This sample is used while creation of item immediately is high-priced.
For example, an item is to be created after a costly database operation.
We can cache the item, returns its clone on subsequent request and update the database as and when wanted thus reducing database calls.
Java-Springs Tutorial
Question 17. What Is Adapter Pattern?

Answer :

Adapter pattern works as a bridge between  incompatible interfaces.
This sample involves a unmarried magnificence which is accountable to sign up for functionalities of independent or incompatible interfaces.
An instance of Adapter pattern:

A actual existence instance can be a case of card reader which acts as an adapter between memory card and a pc.
You plugin the reminiscence card into card reader and card reader into the pc in order that memory card can be study through laptop.
Java applet Interview Questions
Question 18. What Is Bridge Pattern?

Answer :

Bridge is used while we need to decouple an abstraction from its implementation in order that the 2 can range independently.
This kind of design pattern comes underneath structural sample as this pattern decouples implementation class and summary magnificence through imparting a bridge structure among them.
This pattern includes an interface which acts as a bridge which makes the capability of concrete instructions impartial from interface implementer lessons.
Both kinds of instructions can be altered structurally without affecting each other.
J2EE Interview Questions
Question 19. What Is Filter Pattern?

Answer :

Filter pattern or Criteria pattern is a layout pattern that permits builders to filter a hard and fast of items the usage of extraordinary standards and chaining them in a decoupled manner through logical operations.

This kind of design sample comes beneath structural sample as this pattern combines a couple of criteria to reap single criteria.

Java Tutorial
Question 20. What Is Composite Pattern?

Answer :

Composite sample is used wherein we want to treat a set of objects in comparable way as a single object.
Composite sample composes objects in time period of a tree shape to represent element as well as entire hierarchy.
This type of design sample comes under structural pattern as this sample creates a tree structure of institution of gadgets.
This sample creates a class that incorporates group of its very own objects.
This elegance provides approaches to adjust its group of same objects.
Java Interview Questions
Question 21. What Is Decorator Pattern?

Answer :

Decorator pattern permits a user to add new functionality to an existing item without altering its structure.
This kind of design pattern comes under structural sample as this sample acts as a wrapper to present magnificence.
This pattern creates a decorator magnificence which wraps the unique magnificence and gives extra functionality preserving elegance techniques signature intact.
Question 22. What Is Facade Pattern?

Answer :

Facade pattern hides the complexities of the device and affords an interface to the patron the usage of which the customer can access the device.
This form of design pattern comes below structural sample as this pattern provides an interface to present device to cover its complexities.
This sample involves a single magnificence which offers simplified methods required by using client and delegates calls to strategies of present device lessons.
Java 8 Tutorial
Question 23. What Is Flyweight Pattern?

Answer :

Flyweight pattern is often used to lessen the wide variety of items created and to decrease memory footprint and increase performance.
This form of layout sample comes under structural pattern as this pattern provides methods to decrease item rely as a consequence enhancing the object shape of application.
Flyweight sample attempts to reuse already existing comparable kind gadgets by means of storing them and creates new object when no matching item is discovered.
Java eight Interview Questions
Question 24. What Is Proxy Pattern?

Answer :

In proxy pattern, a class represents capability of every other class.
This form of design pattern comes under structural sample.
In proxy pattern, we create item having unique object to interface its functionality to outer international.
Core Java Interview Questions
Question 25. What Is Chain Of Responsibility Pattern?

Answer :

As the call shows, the chain of duty sample creates a chain of receiver gadgets for arequest.
This pattern decouples sender and receiver of a request primarily based on sort of request.
This pattern comes under behavioral styles.
In this pattern, commonly every receiver incorporates connection with any other receiver.
If one object can't handle the request then it passes the same to the next receiver and so forth.
Question 26. What Is Command Pattern?

Answer :

Command sample is a statistics driven layout sample and falls beneath behavioral sample category.
A request is wrapped underneath an object as command and surpassed to invoker object.
Invoker item seems for the ideal object that may deal with this command and passes the command to the corresponding item which executes the command.
Java Programmer Interview Questions
Question 27. What Is Interpreter Pattern?

Answer :

Interpreter sample affords a manner to evaluate language grammar or expression.
This sort of pattern comes beneath behavioral sample.
This sample includes implementing an expression interface which tells to interpret a specific context.
JSP Interview Questions
Question 28. Give An Example Where Interpreter Pattern Is Used?

Answer :

This sample is utilized in SQL parsing, symbol processing engine etc.

Question 29. What Is Iterator Pattern?

Answer :

Iterator sample may be very usually used design pattern in Java and.Net programming surroundings.
This sample is used to get a way to get admission to the elements of a collection object in sequential way without any need to recognize its underlying representation.
Iterator sample falls beneath behavioral pattern category.
Question 30. What Are The Entities Of Service Locator Pattern?

Answer :

Following are the entities of this kind of design sample:

Service - Actual Service in an effort to process the request. Reference of such carrier is to be seemed upon in JNDI server.
Context / Initial Context - JNDI Context contains the reference to service used for lookup motive.
Service Locator - Service Locator is a single factor of contact to get services through JNDI research caching the services.
Cache - Cache to shop references of offerings to reuse them.
Client - Client is the object that invokes the offerings through ServiceLocator.
Question 31. What Is Mediator Pattern?

Answer :

Mediator sample is used to reduce communique complexity between a couple of objects or training.
This pattern offers a mediator magnificence which normally handles all of the communications among exceptional lessons and helps clean upkeep of the code by using free coupling.
Mediator sample falls beneath behavioral sample category.
Question 32. What Is Memento Pattern?

Answer :

Memento sample is used to restore state of an object to a preceding state.
Memento pattern falls below behavioral pattern class.
Question 33. Name The Actor Classes Used In Memento Pattern?

Answer :

Memento sample makes use of 3 actor instructions.
Memento carries kingdom of an object to be restored.
Originator creates and stores states in Memento items and Caretaker object is responsible to repair object country from Memento.
Java-Springs Interview Questions
Question 34. What Is Observer Pattern?

Answer :

Observer sample is used when there is one-to-many relationship among objects such as though one item is changed, its depenedent items are to be notified automatically.
Observer sample falls below behavioral pattern class.
Question 35. Name The Actor Classes Used In Observer Pattern?

Answer :

Observer pattern makes use of 3 actor training. Subject, Observer and Client.
Subject is an object having strategies to connect and detach observers to a consumer item.
We have created an abstract class Observer and a concrete magnificence Subject that is extending class Observer.
Question 36. What Is State Pattern?

Answer :

In State sample a class conduct modifications primarily based on its state.
This type of design sample comes beneath behavior pattern.
In State pattern, we create items which constitute various states and a context item whose conduct varies as its kingdom object modifications.
JMS(Java Message Service) Interview Questions
Question 37. What Is Null Object Pattern?

Answer :

In Null Object pattern, a null object replaces check of NULL object example.
Instead of setting if check for a null price, Null Object reflects a do not anything courting.
Such Null object can also be used to offer default behaviour in case data isn't to be had.
In Null Object pattern, we create an abstract elegance specifying various operations to be completed, concrete lessons extending this elegance and a null object magnificence presenting do nothing implemention of this elegance and will be used seemlessly where we need to check null value.
Question 38. What Is Strategy Pattern?

Answer :

In Strategy sample, a class conduct or its algorithm may be changed at run time.
This type of design pattern comes below behavior pattern.
In Strategy sample, we create gadgets which represent diverse strategies and a context object whose behavior varies as per its strategy item.
The approach item adjustments the executing algorithm of the context item.
Question 39. What Is Template Pattern?

Answer :

In Template pattern, an abstract elegance exposes described ways/templates to execute its techniques.
Its subclasses can override the method implementation as in step with want however the invocation is to be in the equal manner as described by way of an summary elegance.
This sample comes beneath behavior pattern class.
Question 40. What Is Visitor Pattern?

Answer :

In Visitor sample, we use a traveller class which modifications the executing set of rules of an detail class.
By this way, execution algorithm of detail can range as and whilst traveler varies.
This pattern comes under conduct pattern class.
As consistent with the pattern, element object has to simply accept the visitor item so that visitor object handles the operation on the element object.
Java applet Interview Questions
Question 41. What Is Mvc Pattern?

Answer :

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

Model - Model represents an object or JAVA POJO wearing records. It can also have common sense to replace controller if its facts changes.
View - View represents the visualization of the information that version incorporates.
Controller - Controller acts on both model and view. It controls the facts circulate version item and updates the view on every occasion statistics adjustments. It continues view and model separate.
Question forty two. What Is Business Delegate Pattern?

Answer :

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

It is essentially use to reduce communication or remote research capability to commercial enterprise tier code in presentation tier code.

In commercial enterprise tier we've got following entities:

Client - Presentation tier code may be JSP, servlet or UI java code.
Business Delegate - A single access factor class for consumer entities to provide get admission to to Business Service methods.
LookUp Service - Lookup provider object is responsible to get relative commercial enterprise implementation and provide enterprise item get admission to to enterprise delegate item.
Business Service - Business Service interface. Concrete training put in force this enterprise carrier to offer actual business implementation logic.
Java Interview Questions
Question 43. What Is Composite Entity Pattern?

Answer :

Composite Entity sample is used in EJB endurance mechanism :

A Composite entity is an EJB entity bean which represents a graph of objects.
When a composite entity is updated, internally based gadgets beans get updated routinely as being managed via EJB entity bean.
Following are the contributors in Composite Entity Bean:

Composite Entity - It is primary entity bean. It can be coarse grained or can include a rough grained item for use for staying power cause.
Coarse-Grained Object - This object consists of structured objects. It has its very own life cycle and also manages existence cycle of based items.
Dependent Object - Dependent item is an object which relies upon on coarse grained object for its staying power lifecycle.
Strategies - Strategies represents a way to put into effect a Composite Entity.
Question forty four. What Is Data Access Object Patterndao Pattern?

Answer :

Data Access Object Pattern or DAO sample is used to split low degree records having access to API or operations from excessive level business offerings.

Following are the contributors in Data Access Object Pattern:

Data Access Object Interface - This interface defines the standard operations to be carried out on a version objects.
Data Access Object concrete class - This elegance implements above interface. This class is accountable to get facts from a information supply which may be database / xml or some other garage mechanism.
Model Object or Value Object - This object is straightforward POJO containing get/set techniques to keep information retrieved the usage of DAO elegance.
Question forty five. What Is Front Controller Pattern?

Answer :

The front controller design sample is used to provide a centralized request managing mechanism so that every one requests can be handled via a single handler.

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

Following are the entities of this kind of design pattern:

Front Controller - Single handler for all types of requests coming to the application eitherwebbased/desktopbased.
Dispatcher - Front Controller can also use a dispatcher object that can dispatch the request to corresponding specific handler.
View - Views are the object for which the requests are made.
Question 46. What Is Intercepting Filter Pattern?

Answer :

The intercepting filter design sample is used while we want to perform a little pre-processing / postprocessing with request or response of the application:

Filters are defined and implemented at the request before passing the request to actual goal application.
Filters can do the authentication/ authorization/ logging or tracking of request after which skip the requests to corresponding handlers.
Question 47. What Are The Entities Of Intercepting Filter Pattern?

Answer :

Following are the entities of this type of design sample:

Filter - Filter with the intention to performs certain mission prior or after execution of request by request handler.
Filter Chain - Filter Chain incorporates a couple of filters and help to execute them in described order on the right track.
Target - Target object 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.
Question forty eight. What Is Service Locator Pattern?

Answer :

The provider locator design pattern is used whilst we need to find diverse offerings the use of JNDI research:

Considering high cost of searching up JNDI for a provider, Service Locator sample uses caching technique.
For the first time a carrier is required, Service Locator appears up in JNDI and caches the provider object.
Further lookup or same carrier thru Service Locator is carried out in its cache which improves the overall performance of application to high-quality extent.
Question 49. What Is Observer Design Pattern In Java?

Answer :

Observer layout sample is based on speaking changes in state of object to observers with the intention to take there motion.
Simple instance is a weather machine where alternate in climate should be contemplated in Views to reveal to public.
Here weather item is Subject at the same time as specific perspectives are Observers.
Look on this text for complete instance of Observer pattern in Java.
Question 50. Give Example Of Decorator Design Pattern In Java ? Does It Operate On Object Level Or Class Level?

Answer :

Decorator sample enhances functionality of individual item.
Java IO makes use of decorator sample significantly and classical instance is Buffered instructions like BufferedReader and BufferedWriter which enhances Reader and Writer items to carry out Buffer level analyzing and writing for progressed performance.
Question 51. Define Creational Design Patterns?

Answer :

Creational styles are used to outline and describe how objects are created at class instantiation time.
Usually an abstract incredible class contains the information of the instructions which might be instantiated and the patron elegance is unaware of such information.
Singletion pattern, manufacturing unit approach pattern, summary manufacturing unit sample are examples of creational design sample.
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 technique however it's like hard coding the item kind.
If we're one hundred% certain that our item can be of the same elegance all the time, then we use new operator to create an object.
In scenarios wherein the nature of the object can trade consistent with the character of this system, we use creational layout patterns which offer bendy technique for developing class instances.
Question fifty three. Which Object Oriented Method Is Used By The Creational Patterns To Instantiate Object?

Answer :

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

Question fifty four. Define A Factory With Respect To Software Development?

Answer :

Object construction is referred as a factory.
It is used to isolate the creation of items from their utilization.
If you are the use of manufacturing facility strategies for objects creation, then the new derived types will motive no code trade for your instructions that are using factories.
Question 55. When Will You Use A Factory Pattern?

Answer :

The factory sample is preferred within the following instances: - a category does not know which elegance of items it ought to create - manufacturing facility pattern can be used where we want to create an item of any individual of sub-instructions depending at the records provided

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

Answer :

This design pattern query is requested on Java interview not simply to test familiarity with Composite sample but additionally, whether or not candidate has real existence experience or no longer.
Composite sample is likewise a core Java design pattern, which permits you to deal with both complete and part object to treat in comparable manner.
Client code, which offers with Composite or man or woman object doesn't differentiate on them, it is viable due to the fact Composite magnificence additionally enforce same interface as there individual component.
One of the best example of Composite pattern from JDK is JPanel class, which is each Component and Container.
When paint() method is known as on JPanel, it internally called paint() approach of person additives and let them draw themselves.
On 2nd part of this layout pattern interview query, be truthful, when you have used then say sure, in any other case say which you are acquainted with idea and used it by means of your personal.
By the way constantly keep in mind, giving an example out of your challenge creates better impact.
Question 57. What Is Singleton Pattern In Java?

Answer :

Singleton pattern in Java is a sample which lets in most effective one instance of Singleton elegance to be had in complete application.

Question 58. Can You Write Thread-secure Singleton In Java?

Answer :

There are a couple of ways to put in writing thread-safe singleton in Java e.G with the aid of writing singleton the use of double checked locking, with the aid of the use of static Singleton instance initialized at some point of magnificence loading. By the manner the usage of Java enum to create thread-secure singleton is maximum simple manner.

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

Answer :

Factory sample used to create item by supplying static factory methods. There are many advantage of supplying manufacturing facility techniques e.G. Caching immutable objects, easy to introduce new gadgets and so on.

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

Answer :

Observer sample is based upon notification, there are two sorts of item Subject and Observer.Whenever there is trade on concern's nation observer will acquire notification.




CFG