0% found this document useful (0 votes)
184 views

Java Interview Questions

Inheritance in Java allows one class to acquire properties and behaviors of another class. There are three main types of inheritance: single, multilevel, and hierarchical. Polymorphism allows objects to take on multiple forms and is achieved through method overloading and overriding. Encapsulation hides implementation details within a class through public methods and properties.

Uploaded by

Sanjiv Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views

Java Interview Questions

Inheritance in Java allows one class to acquire properties and behaviors of another class. There are three main types of inheritance: single, multilevel, and hierarchical. Polymorphism allows objects to take on multiple forms and is achieved through method overloading and overriding. Encapsulation hides implementation details within a class through public methods and properties.

Uploaded by

Sanjiv Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 82

Question: What is Inheritance in java? It’s benefits and types.

Answer: Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object. Purpose or benefits to use inheritance in
java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical. In java programming, multiple and hybrid inheritance is supported
through interface only.

Single Inheritance is the simple inheritance of all, when a class extends another class
(Only one class) then we call it as Single inheritance.

Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented
Programming languages such as Java, Small Talk, C# etc. (C++ Supports Multiple
Inheritances).

In Multilevel Inheritance a derived class will be inheriting a parent class and as well
as the derived class act as the parent class to other class.

In Hierarchical inheritance one parent class will be inherited by many sub classes.

Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface we can
achieve this.

Question: What is polymorphism in java and it’s types? Also give a real example.

Answer: Polymorphism is the ability of an object to take on many forms. There are two
types of polymorphism in java - compile time polymorphism and runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding.

Runtime Polymorphism (or Dynamic polymorphism)

Method overriding is a perfect example of runtime polymorphism. In this kind of


polymorphism, reference of class X can hold object of class X or an object of any sub
classes of class X. For e.g. if class Y extends class X then both of the following
statements are valid:

Y obj = new Y();


//Parent class reference can be assigned to child object
X obj = new Y();
Since in method overriding both the classes (base class and child class) has same method,
compile doesn’t figure out which method to call at compile-time. In this case JVM (java
virtual machine) decides which method to call at runtime that’s why it is known as
runtime or dynamic polymorphism.

Compile time Polymorphism (or Static polymorphism)

Compile time polymorphism is nothing but the method overloading in java. In simple
terms we can say that a class can have more than one method with same name but with
different number of arguments or different types of arguments or both.

Question: What is encapsulation in java?

Answer: Encapsulation is also known as “data hiding”. Objects encapsulate data and
implementation details. To the outside world, an object is a black box that exhibits
a certain behavior. An object exposes its behavior by means of public methods or
functions. The whole idea behind encapsulation is to hide the implementation details
from users.

Question: What are rules of overriding in java?


Answer:

The Dog’s move() method is called the overriding method.

The Animal’s move() method is called the overridden method.

Rule #1: Only inherited methods can be overridden.

Rule #2: Final and static methods cannot be overridden.

Rule #3: The overriding method must have same argument list.

Rule #4: The overriding method must have same return type (or subtype).

Rule #5: The overriding method must not have more restrictive access modifier.

This rule can be understood as follows:

If the overridden method is has default access, then the overriding one must be
default, protected or public.

If the overridden method is protected, then the overriding one must


be protected or public.

If the overridden method is public, then the overriding one must be only public.

In other words, the overriding method may have less restrictive (more relaxed) access
modifier.

Rule #6: The overriding method must not throw new or broader checked exceptions.
This rule does not apply in case of unchecked exception.
In other words, the overriding method may throw fewer or narrower checked exceptions,
or any unchecked exceptions.

Rule #7: Use the super keyword to invoke the overridden method from a subclass.
It’s very common that a subclass extends a super class behavior rather than re-
implementing the behavior from scratch. In such case, invoke the super class method in
the following form:
super.overriddenMethodName()

Rule #8: Constructors cannot be overridden.

Rule #9: Abstract methods must be overridden by the first concrete (non-abstract)
subclass.

Rule #10: A static method in a subclass may hide another static one in a superclass,
and that’s called hiding.

Rule #11: The synchronized modifier has no effect on the rules of overriding.

Rule #12: The strictfp modifier has no effect on the rules of overriding.
Question: What are rules of overloading in java?

Answer: First and important rule to overload a method in java is to change method
signature. Method signature is made of number of arguments, type of arguments and
order of arguments if they are of different types.

Return type of method is never part of method signature, so only changing the return
type of method does not amount to method overloading. In below code example
method signature is same. That is the reason it gives compile time error.

Thrown exceptions from methods are also not considered when overloading a method.
So your overloaded method throws the same exception, a different exception or it simply
does not throw any exception. No effect at all on method loading. In below code
example method signature is same as above. So, it gives compile time error.

Question: What is Aggregation in java and why use it?


Answer: If a class has an entity reference, it is known as Aggregation. Aggregation
represents HAS-A relationship. Consider a situation, Employee object contains many
information such as id, name, email Id etc. It contains one more object named address,
which contains its own information such as city, state, country, zip code etc. as given
below.

For Code Reusability. Code reuse is also best achieved by aggregation when there is no
is-a relationship. Inheritance should be used only if the relationship IS-A is maintained
throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Question: What is composition? What is difference between aggregation and


composition?

Answer: Composition is a "has-a" relationship. You do composition by having an


instance of another class C as a field of your class, instead of extending C. Composition
is a special case of aggregation. In a more specific manner, a restricted aggregation is
called composition. Composition is more restrictive. When there is a composition
between two objects, the composed object cannot exist without the other object. This
restriction is not there in aggregation. Though one object can contain the other object,
there is no condition that the composed object must exist. The existence of the composed
object is entirely optional in case of aggregation.

Example: A Library contains students and books. Relationship between library and
student is aggregation. Relationship between library and book is composition. A student
can exist without a library and therefore it is aggregation. A library cannot exist without a
book and therefore it’s a composition.

Question: What is association in java?

Answer: Association is a relationship between two objects. In other words, association


defines relationship like one-to-one, one-to-many, many-to-one, and many-to-many. All
these words define an association between objects.

Question: Why constructor cannot be static or final?


Answer: Everything that is marked static belongs to the class only, for example static
method cannot be inherited in the sub class because they belong to the class in which
they have been declared. Since each constructor is being called by its subclass during
creation of the object of its subclass, so if you mark constructor as static the subclass will
not be able to access the constructor of its parent class because it is marked static and
thus belong to the class only. This will violate the whole purpose of inheritance concept
and that is reason why a constructor cannot be static or final.

Question: What happen when we declare private constructor in java?

Answer: It means that constructor would not be accessible outside of your class so other
classes would not be able to call it. Only members of your class will be able to create its
object.

For Example:

Question: Can we overload main() method in java?

Answer: yes, you can overload, nothing stops from overloading, but JVM will always
call the original main method, it will never call your overloaded main method.

Question: Can we override main() method in java?


Answer: No, because main is a static method and static method cannot be overridden in
Java.

Question: Why Java is not pure Object Oriented language?

Answer: Java is not said to be pure object oriented because it support primitive types
such as int, byte, short, long etc. I believe it brings simplicity to the language while
writing our code. As we know, for all the primitive types we have wrapper classes such as
Integer, Long etc that provides some additional methods.

Question: What is Marker interface?

Answer: A marker interface is an empty interface without any method but used to force
some functionality in implementing classes by Java. Some of the well known marker
interfaces are Serializable and Cloneable.

Question: Serialization and Deserialization in Java.


Question: transient Keyword

Question: What are Wrapper classes?

Answer: Java wrapper classes are the Object representation of eight primitive types in
java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and
unboxing allows easy conversion between primitive types and their corresponding
wrapper classes.

Question: An abstract class cannot be instantiated then why does it have the
constructor?

Answer: Every class internally extends Object class by default. So, if abstract class
doesn’t contain constructor we cannot access Object class constructor or we cannot create
constructor for our subclasses. Calling constructor not mean create object every time
although creating object always call constructor.
Constructors do not create objects. They initialize objects. The ‘new’ operator creates
objects.

Question: Why do we need to override hashcode and equals method?

Answer: The default implementation of Object's equals() is

public boolean equals(Object obj) {


return (this == obj);
}

Which means two objects will be considered equal only if they have the same memory
address which will be true only if you are comparing an object with itself. But you might
want to consider two objects the same if they have the same value for one or more of
their properties.

So you will override equals() in these situations and you would give your own conditions
for equality.
As long as you don't use "Hash" based Collections on your user-defined class, it is fine.
But some time in the future you might want to use HashMap or HashSet and if you
don't override and "correctly implement" hashCode(), these Hash based collection won't
work as intended.

Question: Describe Java design patterns.

Answer: Java Design Patterns are divided into three categories–creational, structural,
and behavioral design patterns.

Christopher Alexander was the first person who invented all the below Design Patterns
in 1977. But later the Gang of Four - Design patterns, elements of reusable object-
oriented software book was written by a group of four persons named as Erich Gamma,
Richard Helm, Ralph Johnson and John Vlissides in 1995. That's why all the below 23
Design Patterns are known as Gang of Four (GoF) Design Patterns.

Creational Design Patterns


Creational design patterns provide solution to instantiate an object in the best possible
way for specific situations.

Singleton Design Pattern


Definition: One instance of a class or one value accessible globally in an application.

Where to use & benefits

 Ensure unique instance by defining class final to prevent cloning.


 May be extensible by the subclass by defining subclass final.
 Make a method or a variable public or/and static.
 Access to the instance by the way you provided.
 Well control the instantiation of a class.
 Define one value shared by all instances by making it static.
 Related patterns include

Abstract factory, which is often used to return unique objects.

Builder, which is used to construct a complex object, whereas a singleton is used to create
a globally accessible object.

Prototype, which is used to copy an object, or create an object from its prototype,
whereas a singleton is used to ensure that only one prototype, is guaranteed.

Example

One file system, one window manager, one printer spooler, one Test engine, one
Input/output socket and etc.

To design a Singleton class, you may need to make the class final like java.Math, which
is not allowed to subclass, or make a variable or method public and/or static, or make all
constructors private to prevent the compiler from creating a default one.
Second Example-
Prototype Design Pattern

Definition: Cloning an object by reducing the cost of creation.

Where to use & benefits

 When there are many subclasses that differ only in the kind of objects,
 A system needs independent of how its objects are created, composed, and
represented.
 Dynamic binding or loading a method.
 Use one instance to finish job just by changing its state or parameters.
 Add and remove objects at runtime.
 Specify new objects by changing its structure.
 Configure an application with classes dynamically.
 Related patterns include

Abstract Factory, which is often used together with prototype. An abstract factory may
store some prototypes for cloning and returning objects.
Composite, which is often used with prototypes to make a part-whole relationship.
Decorator, which is used to add additional functionality to the prototype.
Notice that the clone method is overridden to provide a deep copy of the employees list.
Here is the test program that will show the benefit of prototype pattern usage.
Factory Method Design Pattern

Definition: Factory design pattern is used when we have a super class with multiple sub-
classes and based on input, we need to return one of the sub-classes. This pattern takes
out the responsibility of instantiation of a class from client program to the factory class.

Where to use & benefits

 Connect parallel class hierarchies.


 A class wants its subclasses to specify the object.
 A class cannot anticipate its subclasses, which must be created.
 A family of objects needs to be separated by using shared interface.
 The code needs to deal with interface, not implemented classes.
 Hide concrete classes from the client.
 Factory methods can be parameterized.
 The returned object may be either abstract or concrete object.
 Providing hooks for subclasses is more flexible than creating objects directly.
 Follow naming conventions to help other developers to recognize the code structure.
 Related patterns include

Abstract Factory, which is a layer higher than a factory method.


Template method, which defines a skeleton of an algorithm to defer some steps to
subclasses or avoid subclasses
Prototype, which creates a new object by copying an instance, so it reduces subclasses.
Singleton, which makes a returned factory method unique.

Example: Super class in factory pattern can be an interface, abstract class or a normal
java class. For our example, we have super class as abstract class with overridden
toString() method for testing purpose.

Let’s say we have two sub-classes PC and Server with below implementation.
Notice that both the classes are extending Computer class.
Now that we have super classes and sub-classes ready, we can write our factory class.
Here is the basic implementation.
We can keep Factory class Singleton or we can keep the method that returns the subclass
as static. Notice that based on the input parameter, different subclass is created and
returned.

Here is a simple test client program that uses above factory pattern implementation.

Factory Pattern Examples in JDK

1. java.util.Calendar, ResourceBundle and NumberFormat getInstance() methods uses


Factory pattern.
2. valueOf() method in wrapper classes like Boolean, Integer etc.

Builder Design Pattern

Definition: There are three major issues with Factory and Abstract Factory design
patterns when the Object contains a lot of attributes.

1. Too Many arguments to pass from client program to the Factory class that can be error
prone because most of the time, the type of arguments are same and from client side
it’s hard to maintain the order of the argument.
2. Some of the parameters might be optional but in Factory pattern, we are forced to
send all the parameters and optional parameters need to send as NULL.
3. If the object is heavy and its creation is complex, then all that complexity will be part
of Factory classes that is confusing.

Builder pattern solves the issue with large number of optional parameters and
inconsistent state by providing a way to build the object step-by-step and provide a
method that will actually return the final Object.
Builder Pattern Implementation

1. First of all you need to create a static nested class and then copy all the arguments
from the outer class to the Builder class. We should follow the naming convention and
if the class name is Computer then builder class should be named as
ComputerBuilder.
2. The Builder class should have a public constructor with all the required attributes as
parameters.
3. Builder class should have methods to set the optional parameters and it should return
the same Builder object after setting the optional attribute.
4. The final step is to provide a build() method in the builder class that will return the
Object needed by client program. For this we need to have a private constructor in the
Class with Builder class as argument.

Here is the sample code where we have a Computer class and ComputerBuilder class to
build it.

Where to use & benefits

 Make a complex object by specifying only its type and content. The built object is
shielded from the details of its construction.
 Want to decouple the process of building a complex object from the parts that make
up the object.
 Isolate code for construction and representation.
 Give you finer control over the construction process.
 Related patterns include

Abstract Factory, which focuses on the layer over the factory pattern (may be simple or
complex), whereas a builder pattern focuses on building a complex object from other
simple objects. Composite, which is often used to build a complex object.
Notice that Computer class has only getter methods and no public constructor, so the only
way to get a Computer object is through the ComputerBuilder class. Here is a test
program showing how to use Builder class to get the object.

Abstract Factory Design Pattern

Definition: Abstract Factory pattern is similar to Factory pattern and it’s factory of
factories. If you are familiar with factory design pattern in java, you will notice that we
have a single Factory class that returns the different sub-classes based on the input
provided and factory class uses if-else or switch statement to achieve this.

In Abstract Factory pattern, we get rid of if-else block and have a factory class for each
sub-class and then an Abstract Factory class that will return the sub-class based on the
input factory class.

Where to use & benefits


 Creates families of related or dependent objects like Kit.
 Provides a class library of products, exposing interface not implementation.
 Needs to isolate concrete classes from their super classes.
 A system needs independent of how its products are created, composed, and
represented.
 Try to enforce a constraint.
 An alternative to Facade to hide platform-specific classes
 Easily extensible to a system or a family
 Related patterns include
Factory method, which is often implemented with an abstract factory.
Singleton, which is often implemented with an abstract factory.
Prototype, which is often implemented with an abstract factory.
Façade, which is often used with an abstract factory by providing an interface for creating
implementing class.
Factory Classes for Each sub-class
First of all we need to create an Abstract Factory interface or abstract class.

Notice that createComputer() method is returning an instance of super class Computer.


Now our factory classes will implement this interface and return their respective sub-
class.

Similarly we will have a factory class for Server sub-class.


Now we will create a consumer class that will provide the entry point for the client
classes to create sub-classes.

Notice that it’s a simple class and getComputer method is accepting


ComputerAbstractFactory argument and returning Computer object. At this point the
implementation must be getting clear.
Let’s write a simple test method and see how to use the abstract factory to get the
instance of sub-classes.
Structural Design Patterns

Structural patterns provide different ways to create a class structure, for example using
inheritance and composition to create a large object from small objects.

Adapter Pattern

Definition: Adapter design pattern is one of the structural design patterns and it’s used so
that two unrelated interfaces can work together. The object that joins these unrelated
interfaces is called an Adapter. As a real life example, we can think of a mobile charger as
an adapter because mobile battery needs 3 volts to charge but the normal socket produces
either 120V (US) or 240V (India). So the mobile charger works as an adapter between
mobile charging socket and the wall socket.

Where to use & benefits

 Try to match an interface (WindowAdapter, etc.)


 Make unrelated classes work together.
 Multiple compatibility.
 Increase transparency of classes.
 Make a pluggable kit.
 Delegate objects.
 Highly class reusable.
 Achieve the goal by inheritance or by composition
 Related patterns include

Proxy, who provides the same interface as its subject, whereas an adapter provides a
different interface to the object it adapts.
Decorator, which focuses on adding new functions to an object, whereas an adapter
coordinates two different objects.
Bridge, which tries to separate an interface from its implementation and make an object
vary independently, whereas an adapter tries to change and cooperate the interface of an
object.

So first of all we will have two classes – Volt (to measure volts) and Socket
(producing constant volts of 120V).
Two Way Adapter Pattern
While implementing Adapter pattern, there are two approaches – class adapter and object
adapter, however both these approaches produce same result.

1. Class Adapter – This form uses java inheritance and extends the source interface, in
our case Socket class.
2. Objects Adapter – This form uses Java Composition and adapter contains the
source object.

Class Adapter Implementation


Here is the class adapter approach implementation of our adapter.

Object Adapter Implementation

Here is the Object adapter implementation of our adapter.


Notice that both the adapter implementations are almost same and they implement the
SocketAdapter interface. The adapter interface can also be an abstract class. Here is a
test program to consume our adapter implementation.
Composite Design Pattern

Definition: Build a complex object out of elemental objects and itself like a tree
structure.
Composite pattern is one of the Structural design patterns and is used when we have to
represent a part-whole hierarchy. When we need to create a structure in a way that the
objects in the structure has to be treated the same way, we can apply composite design
pattern.

Let’s understand it with a real life example – A diagram is a structure that consists of
Objects such as Circle, Lines, Triangle etc. and when we fill the drawing with color (say
Red), the same color also gets applied to the Objects in the drawing. Here drawing is
made up of different parts and they all have same operations.

Composite Pattern consists of following objects.

1. Base Component – Base component is the interface for all objects in the
composition, client program uses base component to work with the objects in the
composition. It can be an interface or an abstract class with some methods common
to all the objects.
2. Leaf – Defines the behavior for the elements in the composition. It is the building
block for the composition and implements base component. It doesn’t have references
to other Components.
3. Composite – It consists of leaf elements and implements the operations in base
component.

Base Component

Base component defines the common methods for leaf and composites; we can create a
class Shape with a method draw (String fillColor) to draw the shape with given color.

Leaf Objects

Leaf implements base component and these are the building block for the composite. We
can create multiple leaf objects such as Triangle, Circle etc.
Composite

A composite object contains group of leaf objects and we should provide some helper
methods to add or delete leafs from the group. We can also provide a method to remove
all the elements from the group.
Notice that composite also implements component and behaves similar to leaf except that
it can contain group of leaf elements. Our composite pattern implementation is ready and
we can test it with a client program.
Proxy Pattern

Definition: Proxy pattern intent is to “Provide a surrogate or placeholder for another


object to control access to it”. The definition itself is very clear and proxy pattern is used
when we want to provide controlled access of functionality.

Let’s say we have a class that can run some command on the system. Now, if we are
using it, it’s fine but if we want to give this program to a client application, it can have
severe issues because client program can issue command to delete some system files or
change some settings that you don’t want.

Flyweight Pattern

Definition: Flyweight design pattern is used when we need to create a lot of Objects of a
class. Since every object consumes memory space that can be crucial for low memory
devices, such as mobile devices or embedded systems, flyweight design pattern can be
applied to reduce the load on memory by sharing objects. String Pool implementation in
java is one of the best example of Flyweight pattern implementation.

Where to use & benefits

 Need to instantiate a large amount of small and fine-grained classes.


 Need icons to represent object?
 An object extrinsic state can be shared by classes.
 Reduce the number of objects created, decrease memory footprint and increase
performance.
 Increase runtime cost associated with transferring, finding, or computing extrinsic
data.
 Related patterns include

Composite, which supports recursive structures, whereas a flyweight is often applied on


it.
Factory Method, which produces specific object upon requirement, whereas a flyweight
uses it to reduce objects.
State, which allows an object to alter its behavior when its internal state is changed,
whereas a flyweight is best implemented on it.
Strategy, which allows an algorithm vary independently to suit its needs, whereas a
flyweight is based on such strategy.
Flyweight Pattern Example in JDK

All the wrapper classes valueOf() method uses cached objects showing use of Flyweight
design pattern. The best example is Java String class String Pool implementation.

Facade Pattern

Definition: Facade Pattern is used to help client applications to easily interact with the
system. Suppose we have an application with set of interfaces to use MySql/Oracle
database and to generate different types of reports, such as HTML report, PDF report etc.
So we will have different set of interfaces to work with different types of database. Now a
client application can use these interfaces to get the required database connection and
generate reports. But when the complexity increases or the interface behavior names are
confusing, client application will find it difficult to manage it. So we can apply Facade
pattern here and provide a wrapper interface on top of the existing interface to help client
application.

Bridge Pattern
Definition: When we have interface hierarchies in both interfaces as well as
implementations, then builder design pattern is used to decouple the interfaces from
implementation and hiding the implementation details from the client programs. Like
Adapter pattern, it’s one of the Structural design patterns.

The implementation of bridge design pattern follows the notion to prefer Composition
over inheritance.
Decorator Pattern
Definition: Decorator design pattern is used to modify the functionality of an object at
runtime. At the same time other instances of the same class will not be affected by this, so
individual object gets the modified behavior. Decorator design pattern is one of the
structural design patterns (such as Adapter Pattern, Bridge Pattern, Composite Pattern)
and uses abstract classes or interface with composition to implement.

We use inheritance or composition to extend the behavior of an object but this is done at
compile time and it’s applicable to all the instances of the class. We can’t add any new
functionality of remove any existing behavior at runtime – this is when Decorator pattern
comes into picture.

Behavioral Design Patterns

Behavioral patterns provide solution for the better interaction between objects and how to
provide lose coupling and flexibility to extend easily.

Template Method Pattern

Template Method is a behavioral design pattern and it’s used to create a method stub and
deferring some of the steps of implementation to the subclasses. Template method defines
the steps to execute an algorithm and it can provide default implementation that might be
common for all or some of the subclasses.

Suppose we want to provide an algorithm to build a house. The steps need to be


performed to build a house are – building foundation, building pillars, building walls and
windows. The important point is that we can’t change the order of execution because we
can’t build windows before building the foundation. So in this case we can create a
template method that will use different methods to build the house.

Mediator Pattern

Mediator design pattern is used to provide a centralized communication medium between


different objects in a system. Mediator design pattern is very helpful in an enterprise
application where multiple objects are interacting with each other. If the objects interact
with each other directly, the system components are tightly-coupled with each other that
make maintainability cost higher and not flexible to extend easily. Mediator pattern
focuses on provide a mediator between objects for communication and help in
implementing lose-coupling between objects.

Air traffic controller is a great example of mediator pattern where the airport control
room works as a mediator for communication between different flights. Mediator works
as a router between objects and it can have its own logic to provide way of
communication. Check out Mediator Pattern post for implementation details with
example program.

Chain of Responsibility Pattern

Chain of responsibility pattern is used to achieve lose coupling in software design where
a request from client is passed to a chain of objects to process them. Then the object in
the chain will decide themselves who will be processing the request and whether the
request is required to be sent to the next object in the chain or not.

We know that we can have multiple catch blocks in a try-catch block code. Here every
catch block is kind of a processor to process that particular exception. So when any
exception occurs in the try block, its send to the first catch block to process. If the catch
block is not able to process it, it forwards the request to next object in chain i.e. next
catch block. If even the last catch block is not able to process it, the exception is thrown
outside of the chain to the calling program.

Observer Pattern

Observer design pattern is useful when you are interested in the state of an object and
want to get notified whenever there is any change. In observer pattern, the object that
watch on the state of another object are called Observer and the object that is being
watched is called Subject.

Java provides inbuilt platform for implementing Observer pattern through


java.util.Observable class and java.util.Observer interface. However it’s not widely used
because the implementation is really simple and most of the times we don’t want to end
up extending a class just for implementing Observer pattern as java doesn’t provide
multiple inheritance in classes.

Java Message Service (JMS) uses Observer pattern along with Mediator pattern to allow
applications to subscribe and publish data to other applications.

Strategy Pattern

Strategy pattern is used when we have multiple algorithm for a specific task and client
decides the actual implementation to be used at runtime.

Strategy pattern is also known as Policy Pattern. We defines multiple algorithms and let
client application pass the algorithm to be used as a parameter. One of the best example
of this pattern is Collections.sort() method that takes Comparator parameter. Based on the
different implementations of Comparator interfaces, the Objects are getting sorted in
different ways.
Command Pattern

Command Pattern is used to implement lose coupling in a request-response model. In


command pattern, the request is send to the invoker and invoker pass it to the
encapsulated command object. Command object passes the request to the appropriate
method of Receiver to perform the specific action.

Let’s say we want to provide a File System utility with methods to open, write and close
file and it should support multiple operating systems such as Windows and Unix.

To implement our File System utility, first of all we need to create the receiver classes
that will actually do all the work. Since we code in terms of java interfaces, we can have
FileSystemReceiver interface and its implementation classes for different operating
system flavors such as Windows, Unix, Solaris etc.

State Pattern

State design pattern is used when an Object change its behavior based on its internal
state.

If we have to change the behavior of an object based on its state, we can have a state
variable in the Object and use if-else condition block to perform different actions based
on the state. State pattern is used to provide a systematic and lose-coupled way to achieve
this through Context and State implementations.

Visitor Pattern

Visitor pattern is used when we have to perform an operation on a group of similar kind
of Objects. With the help of visitor pattern, we can move the operational logic from the
objects to another class.

For example, think of a Shopping cart where we can add different type of items
(Elements), when we click on checkout button, it calculates the total amount to be paid.
Now we can have the calculation logic in item classes or we can move out this logic to
another class using visitor pattern. Let’s implement this in our example of visitor pattern.

Interpreter Pattern

Interpreter Pattern is used to defines a grammatical representation for a language and


provides an interpreter to deal with this grammar.

The best example of this pattern is java compiler that interprets the java source code into
byte code that is understandable by JVM. Google Translator is also an example of
interpreter pattern where the input can be in any language and we can get the output
interpreted in another language.

Iterator Pattern

Iterator pattern in one of the behavioral pattern and it’s used to provide a standard way to
traverse through a group of Objects. Iterator pattern is widely used in Java Collection
Framework where Iterator interface provides methods for traversing through a collection.

Iterator pattern is not only about traversing through a collection, we can provide different
kind of iterators based on our requirements. Iterator pattern hides the actual
implementation of traversal through the collection and client programs just use iterator
methods.

Memento Pattern

Memento design pattern is used when we want to save the state of an object so that we
can restore later on. Memento pattern is used to implement this in such a way that the
saved state data of the object is not accessible outside of the object, this protects the
integrity of saved state data.

Memento pattern is implemented with two objects – Originator and Caretaker. Originator
is the object whose state needs to be saved and restored and it uses an inner class to save
the state of Object. The inner class is called Memento and its private, so that it can’t be
accessed from other objects.

J2EE Design Patterns

Model/ View/ Controller (MVC) Design Pattern

Definition: The Model/View/Controller (MVC) is an architecture design pattern. Model


means data, View means representation and Controller works on data and representation.
MVC focuses on decouple the triad relationships among data, representation and
controller.

Where to use & benefits

 Application architecture design.


 Any data related design, including non-visual application.
 Decouple complex object to improve maintainability.
 Increase objects reusability.
 Achieve design flexibility.
 Related patterns include

Almost all patterns can be used with MVC.

History

The Model/View/Controller (MVC) originates from Smalltalk, an OO programming


language.

Core issue

MVC consists of three kinds of objects. The Model is an internal representation of the
data, the View is the screen presentation of GUI, and the Controller coordinates changes
between the Model and View.

Business Delegate Design Pattern

Definition: An intermediate class decouples between presentation-tier clients and


business services.

Where to use & benefits

 Simplify the complicated relationship.


 Reduce coupling.
 Cache results and references to remote business services.
 Cut potentially costly round trips
 Hide the underlying implementation details of business service.
 Related patterns include

Proxy combined to simplify the complexity.

Example: Make a class deal with lookups and exception, acting as a representative of the
client components.

Composite Entity Design Pattern

Definition: Use a coarse-grained interface to manage interactions between fine-grained


or coarse-grained and dependent objects internally. The Composite Entity is a
coarse-grained entity bean. It may be the coarse-grained object or hold a reference
to the coarse-grained object. Also known as Aggregate Entity.
Where to use & benefits

 Combine coarse-grained object and its related dependent objects into a single entity
bean.
 Multiple clients share persistent objects.
 Model a network of related business entities.
 In both local and distributed environment, use remote entity beans to model
dependent business objects or fine-grained objects.
 Improve performance by eliminating the parameter and return value serialization and
data transmission costs.
 Eliminate inter-entity relationships
 Improve manageability by reducing entity beans.
 Improve network performance
 Reduce database schema dependency
 Increase object granularity
 Facilitate composite transfer object creation.
 Overhead of multi-level dependent object graphs.
 Related patterns include

Transfer Object used to return to client and also used to serialize the coarse-grained and
dependent objects tree, or part of the tree, as required.

Session Facade used to manage the inter-entity-bean relationships.

Data Access Object (DAO) Design Pattern

Definition: Adapt a uniform interface to access multiple databases like relational, un-
relational, object-oriented, etc.

Where to use & benefits

 Need to access multiple data sources like legacy systems, B2B, LDAP, and so forth.
 Lack of uniform APIs to address the requirements to access disparate systems.
 Persistent storage APIs vary depending on the product vendor.
 Adapt and encapsulate all access to the data source.
 Hide the data source implementation details from its clients.
 More portable and less code dependencies in components.
 Solve differences in the APIs which is used to access different persistent storage
mechanisms.
 Not useful for container-managed persistence.
 Related patterns include

Factory method -- used to deal with different data sources.

Abstract factory -- used to make an abstract layer of access to data sources.


Transfer object -- used to transport data to and from its clients.

Front Controller Design Pattern

Definition: Using a single component to process application requests.

Where to use & benefits

 JSP or Servlet.
 Design request handling component.
 Channel all requests through a single location.
 Centralize request processing and view selection.
 Reduce business logic in a view
 Improve manageability of security
 Promote code reuse across requests
 Avoid code duplication
 Related patterns include

Decorator use doFilter to decorate or modify one or more requests.


Command combined with multiple requests.
Intercepting Filter both centralize control of certain types of request processing.
Page Controller -- an alternative way.

Example
Design a servlet to deal with all the requests. The logon page is the first request. When
the logon is allowed, the controller will present contents to the user. If the user has further
request by clicking a link or a button, such request will be sent to the controller and the
controller will decide if such request is granted or not, if so, the next page will be
presented to the user, and so on.

Intercepting Filter Design Pattern

Definition: A pluggable component design to intercept incoming requests and outgoing


responses, provide common services in a standard manner (independently) without
changing core processing code.

Where to use & benefits

 Logging and authentication.


 Enhance security.
 Add additional function to existing web application.
 Decorate main process.
 Debug.
 Pre-processing or post-processing for specific clients.
 Uncompressed incoming request.
 Convert input encoding schema.
 Being added or removed transparently or declaratively and triggered automatically
 Improve reusability
 Deployment-time composability
 Each filter is loosely coupled
 Inefficient for information sharing.
 Related patterns include

Front Control better suited to handling core processing.


Template good for template filter strategy
Decorator providing for dynamically pluggable wrappers.

Example
To create a basic filter, you need to:

1. implement Filter interface


2. implement doFilter method
3. call doFilter from FilterChain object
4. register the filter with the appropriate servlets and JSP pages
5. Mapping the filter to specific pages
6. disable the invoker servlet

Service Locator Design Pattern

Definition: Centralizing distributed service object lookups, providing a centralized point


of control, acting as a cache that eliminates redundant lookups.

Where to use & benefits

 Lookup object in JNDI, RMI, JMS, etc.


 Encapsulate any vendor-specific features of lookup process
 Simplify the lookup process
 Improve the performance
 Related patterns include

Singleton combined with service locator to make sure only one lookup object exists.
Example: Use a container as cache to hold the lookup object. One application only
lookups same object once. Doing so will dramatically improve performance. Make sure
the container used is thread-safe.
Transfer Object Design Pattern

Definition: Using a serializable class to act as data carrier, grouping related attributes,
forming a composite value and working as a return type from remote business
method. Also known as Value object.

Where to use & benefits

 Get related values from remote business method.


 Fetch multiple values in one trip.
 Decrease network traffic.
 Minimize latency and server resource usage.
 Related patterns include

Composite view

Example: In the J2EE server, the client tier may make several calls to retrieve data from
the enterprise bean. Even in the same machine, the every call from the client tier to
the server tier is a remote method call. Think about use Transfer Object design
pattern to retrieve related attributes and return a single object instead of each call
just for retrieving a single attribute value. The transfer object is passed by value to
the client. All calls to the transfer object instance are local calls to the client, so such
design saves a lot of network traffic.
Let's say that you have a remote banking system. If the user has five requests one time,
you should design your system to give response once, not five times. You may need to
group all return values from these five requests to an object carrier and then return to
client just once. Once the client program receives the instance of this object, it invokes
the assessors and gets value to display. The total network traffic for one user just once.

Question: What is cloning process?

Answer: Cloning is a process of creating an exact copy of an existing object in the


memory. In java, clone() method of java.lang.Object class is used for cloning process.
This method creates an exact copy of an object on which it is called through field-by-
field assignment and returns the reference of that object. Not all the objects in java are
eligible for cloning process. The objects which implement Cloneable interface are only
eligible for cloning process. Cloneable interface is a marker interface which is used to
provide the marker to cloning process.

Both shallow copy and deep copy are related to this cloning process. The default version
of clone() method creates the shallow copy of an object. To create the deep copy of an
object, you have to override the clone() method.

Question: What is deep and shallow copy in object cloning?

Answer: Shallow copy: The default version of clone() method creates the shallow copy
of an object. The shallow copy of an object will have exact copy of all the fields of
original object. If original object has any references to other objects as fields, then only
references of those objects are copied into clone object, copy of those objects are not
created. That means any changes made to those objects through clone object will be
reflected in original object or vice-versa. Shallow copy is not 100% disjoint from original
object. Shallow copy is not 100% independent of original object. The memory usage is
lower. Example:
Deep copy: Deep copy of an object will have exact copy of all the fields of original
object just like shallow copy. But in additional, if original object has any references to
other objects as fields, then copy of those objects are also created by calling clone()
method on them. That means clone object and original object will be 100% disjoint. They
will be 100% independent of each other. Any changes made to clone object will not be
reflected in original object or vice-versa.
Shallow Copy vs. Deep Copy in Java: Below is the list of differences between shallow
copy and deep copy in java.
Question: Compare JAVA and .NET. Which one is preferable than other.

Answer:

 Assess the complexity of the applications you will be building


Microsoft tools have an edge over Java for building applications that require rich
graphical user interfaces and that deliver content to web browsers. The perception is that
Java servers are better for complex applications supporting higher volumes of users.

 Weigh the importance of application portability to your product, company


Java, with its multi-platform portability, gives you leverage to either negotiate with an
existing vendor or pick the vendor of your choice.

 Investigate outside vendor support

As mentioned above, Java’s strength lies in libraries developed by various third-party


vendors. Similarly there are a bunch of controls and libraries available for .NET as well.
Question: What are differences between throw and throws keyword in java?

Answer: 1. Throws clause is used to declare an exception and throw keyword is used to
throw an exception explicitly.
2. If we see syntax wise then throw is followed by an instance variable and throws is
followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception and throws
clause is used in method declaration (signature).
4. By using Throw keyword in java you cannot throw more than one exception but
using throws you can declare multiple exceptions.

Question: What makes java platform independent?

Answer: Javac – compiler that converts source code to byte code.


JVM - Interpreter that converts byte code to machine language code.
As we know java is both compiler & interpreter based language. Once the java code also
known as source code is compiled, it gets converted to native code known as BYTE
CODE which is portable & can be easily executed on all operating systems. Byte code
generated is basically represented in hexadecimal format. This format is same on every
platform be it Solaris work station or Macintosh, windows or Linux. After compilation,
the interpreter reads the generated byte code & translates it according to the host
machine. Byte code is interpreted by Java Virtual Machine which is available with all the
operating systems we install. So to port Java programs to a new platform all that is
required is to port the interpreter (JVM) and some of the library routines. In other words
JVM or Java virtual machine is platform dependent because it converts byte code into
machine level instruction which is platform specific and that's why you have different
version of JDK and JRE for windows and Linux because both JDK and JRE comes with
Java virtual machine.

Question: What are differences between JVM, JDK and JRE?

Answer: Remember JRE, meant for Java Runtime Environment and JDK stands for Java
Development Kit.

1) Main difference between JRE and JDK is that, you cannot compile Java program using
JRE. Tools required for compiling Java source file to create class files, i.e. javac, comes
with JDK installation.

2) As name suggest JRE is for running Java program and developed as browser plug-in.
In order to run any Java program from browser like Internet Explorer, Mozilla Firefox or
Google Chrome, you need JRE to be installed in your machine and should be enabling on
your browser as well.

3) JRE is meant for users, while JDK is meant for programmers. JRE is enough to run
Java program and JDK is required only if you want to do programming in Java platform.

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides


runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent. The JVM performs following main tasks:
Loads code, Verifies code, Executes code, Provides runtime environment

Question: Java all version history and features.

Answer: Java Versions, Features and History


Released on 23 January 1996, JDK 1.0 version.

Released on 19 February 1997 JDK 1.1 version.


New features in JDK 1.1

1. JDBC (Java Database Connectivity)


2. Inner Classes
3. Java Beans
4. RMI (Remote Method Invocation)
5. Reflection (introspection only)
Released on 8 December 1998 J2SE 1.2 version.
New features in J2SE 1.2

1. Collections framework.
2. Java String memory map for constants.
3. Just In Time (JIT) compiler.
4. Jar Signer for signing Java ARchive (JAR) files.
5. Policy Tool for granting access to system resources.
6. Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and
Java 2D class libraries.
7. Java Plug-in
8. Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
9. Audio support in Applets.
Released on 8 May 2000 J2SE 1.3 version.
New features in J2SE 1.3

1. Java Sound
2. Jar Indexing
3. A huge list of enhancements in almost all the java area.
Released on 6 February 2002 J2SE 1.4 version.
New features in J2SE 1.4

1. XML Processing
2. Java Print Service
3. Logging API
4. Java Web Start
5. JDBC 3.0 API
6. Assertions
7. Preferences API
8. Chained Exception
9. IPv6 Support
10. Regular Expressions
11. Image I/O API
Released on 30 September 2004 J2SE 1.5 version.
New features in J2SE 1.5

1. Generics
2. Enhanced for Loop
3. Autoboxing/Unboxing
4. Enum
5. Varargs
6. Static Import
7. Metadata (Annotations)
8. Instrumentation
Released on 11 December 2006 J2SE 1.6 version.
New features in J2SE 1.6

1. Scripting Language Support


2. JDBC 4.0 API
3. Java Compiler API
4. Pluggable Annotations
5. Native PKI, Java GSS, Kerberos and LDAP support.
6. Integrated Web Services.
7. Lot more enhancements.

Released on 28 July 2011 J2SE 1.7 version.


New features in J2SE 1.7

1. Strings in switch Statement


2. Type Inference for Generic Instance Creation
3. Multiple Exception Handling
4. Support for Dynamic Languages
5. Try with Resources
6. Java nio Package
7. Binary Literals, underscore in literals
8. Diamond Syntax
9. Automatic null Handling

Released on 18th march 2014 JDK 1.8 version.


New features in JDK 1.8

1. Default and Static methods in Interface


2. Lambda Expressions
3. Optional
4. Streams
5. Method References
6. Data Time API
7. Nashorn Javascript Engine
8. Parallel Arrays

Question: Difference between final, finally and finalize.

Answer:
final finally finalize
Final is used to apply Finally is used to place Finalize is used to perform
restrictions on class, method important code, it will be clean up processing just
and variable. Final class executed whether exception before object is garbage
can't be inherited, final is handled or not. You need collected.
method can't be overridden at least try block
and final variable value before finally block.
can't be changed. catch block is optional.
These combinations are
allowed.
1. try catch finally
2. try catch
3. try finally

Final is a keyword. Finally is a block. Finalize is a method.

Question: What is ThreadLocal in java and how to use?

Answer: Thread Local can be considered as a scope of access, like a request scope or
session scope. It's a thread scope. You can set any object in Thread Local and this object
will be global and local to the specific thread which is accessing this object.
 Values stored in Thread Local are global to the thread, meaning that they can be
accessed from anywhere inside that thread. If a thread calls methods from several
classes, then all the methods can see the Thread Local variable set by other methods
(because they are executing in same thread). The value need not be passed explicitly.
It's like how you use global variables.
 Values stored in Thread Local are local to the thread, meaning that each thread will
have its own Thread Local variable. One thread cannot access/modify other thread's
Thread Local variables.

I can point out one use case where I used thread local. Consider you have a Servlet which
calls some business methods. You have a requirement to generate a unique transaction id
for each and every request this servlet process and you need to pass this transaction id to
the business methods, for logging purpose. One solution would be passing this
transaction id as a parameter to all the business methods. But this is not a good solution
as the code is redundant and unnecessary.
To solve that, you can use Thread Local. You can generate a transaction id (either in
servlet or better in a filter) and set it in the Thread Local. After this, what ever the
business method, that this servlet calls, can access the transaction id from the thread
local. This servlet might be servicing more than one request at a time. Since each request
is processed in separate thread, the transaction id will be unique to each thread (local) and
will be accessible from all over the thread's execution (global).
Let’s first have the Context.java file which will hold the transactionId field.
Now create the MyThreadLocal.java file which will act as a container to hold our context
object.

In the above code, you are creating a ThreadLocal object as a static field which can be
used by rest of the code to set/get thread local variables.
Let's create our main class file which will generate and set the transaction ID in thread
local and then call the business method.
Finally, here's the code for the BusinessService.java which will read from thread local
and use the value.

When you run the ThreadLocalDemo file, you'll get the below output:
Thread-0
Thread-1
As you might see, even though we are not explicitly passing the transaction id, the value
can be accessed from the business method and printed on the console. Adding to it, the
transaction ID differs for each thread (0 and 1).

Question: What is UnSupportedClassVersionError in Java?

Answer: Java.lang.UnsupportedClassVersionError is a subclass of


java.lang.ClassFormatError. This is a kind of linking error which occurs during
linking phase accordingly java.lang.ClassFormatError has also derived from
java.lang.LinkageError. As the name suggests "UnSupportedClassVersionError" so
it’s related to unsupported class version. The Version of class file is represented as
major_version.minor_version. This version is used to determine format of class
file in Java. According to Java Virtual Machine specification, “A JVM
implementation can support a class file format of version v if and only if v lies in
some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions
a JVM implementation conforming to a certain release level of the Java platform
may support.” For example: JDK 1.2 supports class file formats from version 45.0
to version 46.0 inclusive. So if a class file has version 48.0 it means that major
version of class file is "48" and minor version is "0", which tells us that JDK 1.4
has been used to compile and generate that class file.
When JVM tries to load a class and found that class file version is not supported it
throws UnSupportedClassVersionError and it generally occurs if a higher JDK
version is used to compile the source file and a lower JDK version is used to run
the program. For example if you compile your java source file in JDK 1.5 and you
will try to run it on JDK 1.4 you will get
error "java.lang.UnsupportedClassVersionError: Bad version number in .class
file [at java.lang.ClassLoader.defineClass1(Native Method)].
But it’s important to note is that vice-versa is not true "you can compile your
program in J2SE 1.4 and run on J2SE 1.5 and you will not get any
UnSupportedClassVersionError". When a higher JDK is used for compilation it
creates class file with higher version and when a lower JDK is used to run the
program it found that higher version of class file not supported at JVM level and
results in java.lang.UnsupportedClassVersionError.
Following are the major version of class file format in standard JDK environment.

JDK 1.1 = 45 JDK 1.7 = 51


JDK 1.2 = 46 JDK 1.8 = 52
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50

Question: What are differences between JDBC Statement, PreparedStatement and


CallableStatement?

Answer: JDBC Statement used for firing static queries (e.g. select * from table). JDBC
Statements can not accept parameters. Statement is suitable for executing DDL
commands - CREATE, drop, alter and truncate in java JDBC. Statement can’t be used for
storing/retrieving image and file in database (i.e. using BLOB, CLOB datatypes) in java
JDBC.

PreparedStatement extends Statement Interface to provide extra


feature. PreparedStatement is used for executing a precompiled SQL statement in java
JDBC. PreparedStatement can be executed repeatedly; it can accept different parameters
at runtime in java JDBC. PreparedStatement is suitable for executing DML commands -
SELECT, INSERT, UPDATE and DELETE in java JDBC. PreparedStatement can be
used for storing/retrieving image and Storing /retrieving file in database (i.e. by using
BLOB, CLOB datatypes) in java JDBC.

CallableStatement extends the PreparedStatement interface.


The CallableStatement is an interface which is used to execute SQL stored procedures,
cursors and functions in java.

Question: Difference between Comparator and Comparable interfaces.

Answer: Implementing Comparable means "I can compare myself with another
object."This is typically useful when there's a single natural default comparison.
Implementing Comparator means "I can compare two other objects." This is typically
useful when there are multiple ways of comparing two instances of a type - e.g. you could
compare people by age, name etc.

Question: Why we override equals() & hashCode()?

Question: What are difference between Web server and Application server?

Answer: 1. Application Server supports distributed transaction and EJB. While Web
Server only supports Servlet and JSP.
2. Application Server can contain web server in them. Most of App server e.g. JBoss or
WAS has Servlet and JSP container.
3. Though it’s not limited to Application Server but they used to provide services
like Connection pooling, Transaction management, messaging, clustering, load
balancing and persistence. Now Apache tomcat also provides connection pooling.

4. In terms of logical difference between web server and application server. Web server is
supposed to provide http protocol level service while application server provides support
to web service and expose business level service e.g. EJB.

4. Application server is heavier than web server in terms of resource utilization.

Question: Important points about this keyword in java.

Answer: 1) this keyword represent current instance of class.

2) You can synchronize on this in synchronized block in Java

synchronized(this){
//this synchronized block will be locked on current instance
}

3) this keyword can be used to call overloaded constructor in java. If used than it must
be first statement in constructor this() will call no argument constructor and
this(parameter) will call one argument constructor with appropriate parameter. Here is
an example of using this() for constructor chaining:

Example of this keyword to call constructor in Java

class Loan{
private double interest;
private String type;

public Loan(){
this(“personal loan”);
}

public Loan(String type){


this.type = type;
this.interest = 0.0;
}
}
4) If member variable and local variable name conflict than this can be used to refer
member variable.
Here is an example of this with member variable:

public Loan(String type, double interest){


this.type = type;
this.interest = interest;
}

Here local variable interest and member variable interest conflict which is easily resolve
by referring member variable as this.interest

5) this is a final variable in Java and you can not assign value to this. this will result in
compilation error:

this = new Loan(); //cannot assign value to final variable : this

6) You can call methods of class by using this keyword as shown in below example.

public String getName(){


return this.toString();
}

7) this can be used to return object. this is a valid return value. Here is an example of
using as return value.

public Loan getLoan(){


return this;
}

8) this can be used to refer static members in Java as well but its discouraged and as per
best practices
This should be used on non static reference.

9) "this" keyword cannot be used in static context i.e. inside static methods or static
initializer block.
If use this inside static context you will get compilation error as shown in below example:

public static void main(String args){


this.toString{}; //compilation error: non static variable this cannot be used in
static context
}
10) this can also be passed as method parameters since it represent current object of
class.

Question: How Hash Map Works In Java?

Answer: HashMap working in Java.

HashMap works on the principle of Hashing. To understand Hashing, we should


understand the three terms first i.e Hash Function, Hash Value and Bucket.

Hash Function, Hash Value and Bucket.


hashCode() function which returns an integer value is the Hash function. The important
point to note that, this method is present in Object class (Mother of all class).

This is the code for the hash function (also known as hashCode method) in Object Class:

public native int hashCode();

The most important point to note from the above line: hashCode method return int
value. So the Hash value is the int value returned by the hash function.

What is bucket?
Answer: A bucket is used to store key value pairs. A bucket can have multiple key-value
pairs. In hash map, bucket used simple linked list to store objects.

Code inside Java API (HashMap class internal implementation) for HashMap get(Obejct
key) method

1. Public V get(Object key)


{
2. if (key ==null)
3. //Some code

4. int hash = hash(key.hashCode());

5. // if key found in hash table then return value


6. // else return null
}

Hash map works on the principle of hashing

HashMap get(Key k) method calls hashCode method on the key object and applies
returned hashValue to its own static hash function to find a bucket location(backing
array) where keys and values are stored in form of a nested class called Entry
(Map.Entry) . So you have concluded that from the previous line that both key and
value is stored in the bucket as a form of Entry object. So thinking that only value is
stored in the bucket is not correct and will not give a good impression on the interviewer.

Whenever we call get( Key k ) method on the HashMap object . First it checks that
whether key is null or not. Note that there can only be one null key in HashMap.
If key is null, then Null keys always map to hash 0, thus index 0.

If key is not null then, it will call hashfunction on the key object, see line 4 in above
method i.e. key.hashCode(), so after key.hashCode() returns hashValue, line 4 looks like

int hash = hash(hashValue)

, and now ,it applies returned hash Value into its own hashing function .

Question: We might wonder why we are calculating the hashvalue again using
hash(hashValue)?

Answer: It defends against poor quality hash functions. Now step 4 final hashvalue is
used to find the bucket location at which the Entry object is stored. Entry object stores
in the bucket like this (hash,key,value,bucketindex) .

Question: What if when two different keys have the same hashcode ?

Answer: equals() method comes to rescue. Here candidate gets puzzled. Since bucket is
one and we have two objects with the same hashcode. Candidate usually forgets that
bucket is a simple linked list.

The bucket is the linked list effectively. It’s not a LinkedList as in a


java.util.LinkedList - It's a separate (simpler) implementation just for the map.

So we traverse through linked list, comparing keys in each entries using


keys.equals() until it return true. Then the corresponding entry object Value is
returned.
Question: When the functions 'equals' traverses through the linked list does it
traverses from start to end one by one...in other words brute method. Or the linked
list is sorted based on key and then it traverses?

Answer: when an element is added/retrieved, same procedure follows:


a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key
b. Pass initial hashvalue as hashValue in hash(hashValue) function, to calculate the final
hashvalue.
c. Final hash value is then passed as a first parameter in the indexFor(int ,int )method.
The second parameter is length which is a constant in HashMap Java Api, represented by
DEFAULT_INITIAL_CAPACITY
The default value of DEFAULT_INITIAL_CAPACITY is 16 in HashMap Java Api.

indexFor(int,int) method returns the first entry in the appropriate bucket. The linked list
in the bucket is then iterated over - (the end is found and the element is added or the key
is matched and the value is returned)
Explanation about indexFor(int,int) is below :

/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
return h & (length-1);
}

The above function indexFor() works because Java HashMaps always have a capacity,
i.e. number of buckets, as a power of 2.
Let's work with a capacity of 256, which is 0x100, but it could work with any power of
2. Subtracting 1
from a power of 2 yields the exact bit mask needed to bitwise-and with the hash to get the
proper bucket index, of range 0 to length - 1.
256 - 1 = 255
0x100 - 0x1 = 0xFF
E.g. a hash of 257 (0x101) gets bitwise-anded with 0xFF to yield a bucket number of 1.

Question: What if when two keys are same and have the same hashcode?
Answer: If key needs to be inserted and already inserted hashkey's hashcodes are same,
and keys are also same (via reference or using equals() method) then override the
previous key value pair with the current key value pair.

The other important point to note is that in Map ,Any class(String etc.) can serve as a
key if and only if it overrides the equals() and hashCode() method .

Question: How will you measure the performance of HashMap?

Answer: According to Oracle Java docs, an instance of HashMap has two parameters that
affect its performance: initial capacity and load factor.

The capacity is the number of buckets in the hash table (HashMap class is roughly
equivalent to Hashtable, except that it is unsynchronized and permits nulls.), and the
initial capacity is simply the capacity at the time the hash table is created.

The load factor is a measure of how full the hash table is allowed to get before its
capacity is automatically increased. When the number of entries in the hash table exceeds
the product of the load factor and the current capacity, the hash table is rehashed (that is,
internal data structures are rebuilt) so that the hash table has approximately twice the
number of buckets.
In HashMap class, the default value of load factor is (0.75).

Question: What is the time complexity of Hashmap get() and put() method ?

Answer: The hashmap implementation provides constant time performance for (get and
put) basic operations
i.e the complexity of get() and put() is O(1) , assuming the hash function disperses the
elements properly among the buckets.

There are several reasons for using nested classes, among them:
1. It is a way of logically grouping classes that are only used in one place.
2. It increases encapsulation.
3. Nested classes can lead to more readable and maintainable code.
4. Child to parent class connection is simpler as it visually illustrates the variables
and methods of each class.

Question: A problem caused by substring() in JDK 6. Or, Substring() Memory leak problem.
Answer: If you have a VERY long string, but you only need a small part each time by
using substring(). This will cause a performance problem, since you need only a small
part, you keep the whole thing. For JDK 6, the solution is using the following, which will
make it point to a real sub string:

x = x.substring(x, y) + ""

substring() in JDK 7
This is improved in JDK 7. In JDK 7, the substring() method actually create a new array
in the heap.

//JDK 7
public String(char value[], int offset, int count)
{
//check boundary
this.value = Arrays.copyOfRange(value, offset, offset + count);
}

public String substring(int beginIndex, int endIndex)


{
//check boundary
int subLen = endIndex - beginIndex;
return new String(value, beginIndex, subLen);
}
Question: What are URI and URL?

Answer: URI identify and URLs locate.


Locators are also identifiers, so every URL is also a URI, but there is URIs which is not
URLs.
Examples

 Roger Pate
This is my name, which is an identifier. It is like a URI, but cannot be a URL, as it tells
you nothing about my location or how to contact me. In this case it also happens to
identify at least 5 other people in the USA alone.

 4914 West Bay Street, Nassau, Bahamas


This is a locator, which is an identifier for that physical location. It is like both a URL and
URI (since all URLs are URIs), and also identifies me indirectly as "resident of..". In this
case it uniquely identifies me, but that would change if I get a roommate.

In summary: a URI identifies, a URL identifies and locates.


Consider a specific edition of Shakespeare's play Romeo and Juliet, of which you have a
digital copy on your home network.
You could identify the text as urn: ISBN: 0-486-27557-4.
That would be a URI, but more specifically a URN because it names the text.
You could also identify the text
as file://hostname/sharename/RomeoAndJuliet.pdf.
That would also be a URI, but more specifically a URL because it locates the text.

Question: Why String and other wrapper classes are considered good keys?

Answer: String, Integer and other wrapper classes are natural candidates
of HashMap key, and String is most frequently used key as well because String is
immutable and final, and overrides equals and hashcode() method. Other wrapper class
also shares similar property. Immutability is required, in order to prevent changes on
fields used to calculate hashCode() because if key object return different hashCode
during insertion and retrieval than it won't be possible to get object from HashMap.
Immutability is best as it offers other advantages as well like thread-safety, if you
can keep your hashCode same by only making certain fields final, then you go for that as
well. Since equals() and hashCode() method is used during retrieval of value object
from HashMap, its important that key object correctly override these methods and follow
contact. If unequal object return different hashcode than chances of collision will be less
which subsequently improve performance of HashMap.

Question: Can we use any custom object as key in HashMap?

Answer: This is an extension of previous questions. Of course you can use any Object as
key in Java HashMap provided it follows equals and hashCode contract and its hashCode
should not vary once the object is inserted into Map. If custom object is Immutable then
this will be already taken care because you cannot change it once created.

Question: Can we use ConcurrentHashMap in place of Hashtable?

Answer: Since we know Hashtable is synchronized but ConcurrentHashMap provides


better concurrency by only locking portion of map determined by concurrency
level. ConcurrentHashMap is certainly introduced as Hashtable and can be used in place
of it but Hashtable provide stronger thread-safety than ConcurrentHashMap.
 Concept of hashing
 Collision resolution in HashMap

 Use of equals () and hashCode () and there importance in HashMap?


 Benefit of immutable object?
 Race condition on HashMap in Java
 Resizing of Java HashMap

Question: How null key is handled in HashMap? Since equals() and hashCode() are
used to store and retrieve values, how does it work in case of null key?

Answer: Null key is handled specially in HashMap, there are two separate method for
that putForNullKey(V value) and getForNullKey(). Later is offloaded version of get() to
look up null keys. Null keys always map to index 0. This null case is split out into
separate methods for the sake of performance in the two most commonly used operations
(get and put), but incorporated with conditionals in others. In
short, equals() and hashcode() method are not used in case of null keys in HashMap.
Here is how nulls are retreived from HashMap

private V getForNullKey() {
if (size == 0) {
return null;
}
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
Let’s take a very simple example. I have a Country class; we are going to use Country
class object as key and its capital name (string) as value. Below example will help you to
understand, how these key value pair will be stored in hashmap.

1. Country.java
1. package org.arpit.java2blog;
2. public class Country {
3.
4. String name;
5. long population;
6.
7. public Country(String name, long population) {
8. super();
9. this.name = name;
10. this.population = population;
11. }
12. public String getName() {
13. return name;
14. }
15. public void setName(String name) {
16. this.name = name;
17. }
18. public long getPopulation() {
19. return population;
20. }
21. public void setPopulation(long population) {
22. this.population = population;
23. }
24.
25. // If length of name in country object is even then return 31(any random number)
and if odd then return 95(any random number).
26. // This is not a good practice to generate hashcode as below method but I am doin
g so to give better and easy understanding of hashmap.
27. @Override
28. public int hashCode() {
29. if(this.name.length()%2==0)
30. return 31;
31. else
32. return 95;
33. }
34. @Override
35. public boolean equals(Object obj) {
36.
37. Country other = (Country) obj;
38. if (name.equalsIgnoreCase((other.name)))
39. return true;
40. return false;
41. }
42.
43. }

2. HashMapStructure.java(main class)

1. import java.util.HashMap;
2. import java.util.Iterator;
3.
4. public class HashMapStructure {
5.
6. /**
7. * @author Arpit Mandliya
8. */
9. public static void main(String[] args) {
10.
11. Country india=new Country("India",1000);
12. Country japan=new Country("Japan",10000);
13.
14. Country france=new Country("France",2000);
15. Country russia=new Country("Russia",20000);
16.
17. HashMap<country tring=""> countryCapitalMap=new HashMap<country tri
ng="">();
18. countryCapitalMap.put(india,"Delhi");
19. countryCapitalMap.put(japan,"Tokyo");
20. countryCapitalMap.put(france,"Paris");
21. countryCapitalMap.put(russia,"Moscow");
22.
23. Iterator<country> countryCapitalIter=countryCapitalMap.keySet().iterator();/
/put debug point at this line
24. while(countryCapitalIter.hasNext())
25. {
26. Country countryObj=countryCapitalIter.next();
27. String capital=countryCapitalMap.get(countryObj);
28. System.out.println(countryObj.getName()+"----"+capital);
29. }
30. }
31. }
32. </country></country></country>

Now put debug point at line 23 and right click on project->debug as-> java application.
Program will stop execution at line 23 then right click on countryCapitalMap then select
watch. You will be able to see structure as below.

Now From above diagram, you can observe following points

1. There is an Entry[] array called table which has size 16.


2. This table stores Entry class's object. HashMap class has a inner class called
Entry.This Entry have key value as instance variable. Let’s see structure of entry class
Entry Structure.

1. static class Entry implements Map.Entry


2. {
3. final K key;
4. V value;
5. Entry next;
6. final int hash;
7. ...//More code goes here
8. }

3. Whenever we try to put any key value pair in hashmap, Entry class object is
instantiated for key value and that object will be stored in above mentioned Entry[]
(table). Now you must be wondering, where will above created Enrty object get stored
(exact position in table)? The answer is, hash code is calculated for a key by calling
Hascode() method. This hashcode is used to calculate index for above Entry[] table.

4. Now, If you see at array index 10 in above diagram, It has an Entry object named
HashMap$Entry.

5. We have put 4 key-values in hashmap but it seems to have only 2!!!!This is because if
two objects have same hashcode, they will be stored at same index. Now question
arises how? It stores objects in a form of LinkedList (logically).
So, how hashcode of above country key-value pairs are calculated?
1. Hashcode for Japan = 95 as its length is odd.
2. Hashcode for India =95 as its length is odd
3. HashCode for Russia=31 as its length is even.
4. HashCode for France=31 as its length is even.

Below diagram will explain LinkedList concept clearly.


So now if you have good understanding of hashmap structure, let’s go through put and
get method.

Put Method:
Let’s see implementation of put method:

1. /**
2. * Associates the specified value with the specified key in this map. If the
3. * map previously contained a mapping for the key, the old value is
4. * replaced.
5. *
6. * @param key
7. * key with which the specified value is to be associated
8. * @param value
9. * value to be associated with the specified key
10. * @return the previous value associated with <tt>key</tt>, or <tt>null</tt>
11. * if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return
12. * can also indicate that the map previously associated
13. * <tt>null</tt> with <tt>key</tt>.)
14. */
15. public V put(K key, V value) {
16. if (key == null)
17. return putForNullKey(value);
18. int hash = hash(key.hashCode());
19. int i = indexFor(hash, table.length);
20. for (Entry<k , V> e = table[i]; e != null; e = e.next) {
21. Object k;
22. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
23. V oldValue = e.value;
24. e.value = value;
25. e.recordAccess(this);
26. return oldValue;
27. }
28. }
29.
30. modCount++;
31. addEntry(hash, key, value, i);
32. return null;
33. }

Now let’s understand above code step by step


1. Key object is checked for null. If key is null then it will be stored at table[0] because
hashcode for null is always 0.
2. Key object's hashcode() method is called and hash code is calculated. This hashcode
is used to find index of array for storing Entry object. It may happen sometimes that,
this hashcode function is poorly written so JDK designer has put another function
called hash() which takes above calculated hash value as argument.

3. indexFor(hash,table.length) is used to calculate exact index in table array for storing


the Entry object.
4. As we have seen in our example, if two key objects have same hashcode(which is
known as collision) then it will be stored in form of linkedlist. So here, we will iterate
through our linkedlist.
If there is no element present at that index which we have just calculated then it will
directly put our Entry object at that index.

If there is element present at that index then it will iterate until it gets Entry->next as null.
Then current Entry object become next node in that linkedlist

What if we are putting same key again, logically it should replace old value. Yes, it will
do that. While iterating it will check key equality by calling equals()
method(key.equals(k)), if this method returns true then it replaces value object with
current Entry's value object.
Get Method:
Let’s see implementation of get now:

1. /**
2. * Returns the value to which the specified key is mapped, or {@code null}
3. * if this map contains no mapping for the key.
4. *
5. * <p>
6. * More formally, if this map contains a mapping from a key {@code k} to a
7. * value {@code v} such that {@code (key==null ? k==null :
8. * key.equals(k))}, then this method returns {@code v}; otherwise it returns
9. * {@code null}. (There can be at most one such mapping.)
10. *
11. * </p><p>
12. * A return value of {@code null} does not <i>necessarily</i> indicate that
13. * the map contains no mapping for the key; it's also possible that the map
14. * explicitly maps the key to {@code null}. The {@link #containsKey
15. * containsKey} operation may be used to distinguish these two cases.
16. *
17. * @see #put(Object, Object)
18. */
19. public V get(Object key) {
20. if (key == null)
21. return getForNullKey();
22. int hash = hash(key.hashCode());
23. for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
24. Object k;
25. if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
26. return e.value;
27. }
28. return null;
29. }

As you got the understanding on put functionality of hashmap. So to understand get


functionality is quite simple. If you pass any key to get value object from hashmap.
1. Key object is checked for null. If key is null then value of Object resides at table[0]
will be returned.
2. Key object's hashcode() method is called and hash code is calculated.

3. indexFor(hash,table.length) is used to calculate exact index in table array using


generated hashcode for getting the Entry object.

4. After getting index in table array, it will iterate through linkedlist and check for key
equality by calling equals() method and if it returns true then it returns the value of
Entry object else returns null.

Key points to Remeber:


 HashMap has a inner class called Entry which stores key-value pairs.
 Above Entry object is stored in Entry[ ](Array) called table
 An index of table is logically known as bucket and it stores first element of linkedlist
 Key object's hashcode() is used to find bucket of that Entry object.
 If two key object’s have same hashcode , they will go in same bucket of table array.
 Key object’s equals() method is used to ensure uniqueness of key object.
 Value object 's equals() and hashcode() method is not used at all

Question: Difference between HashSet and LinkedHashSet and TreeSet.

Answer:
Difference HashSet LinkedHashSet TreeSet
How they work HashSet uses LinkedHashSet uses TreeSet uses TreeMap
internally? HashMap LinkedHashMap internally to store it’s
internally to store internally to store it’s elements.
it’s elements. elements.
Order Of Elements HashSet doesn’t LinkedHashSet TreeSet orders the
maintain any order maintains insertion
elements according to
of elements. order of elements. i.e
supplied Comparator.
elements are placed
If no comparator is
as they are inserted.
supplied, elements
will be placed in their
natural ascending
order.
Performance HashSet gives The performance of TreeSet gives less
better performance LinkedHashSet is performance than the
than the between HashSet and HashSet and
LinkedHashSet and TreeSet. It’s LinkedHashSet as it
TreeSet. performance is almost has to sort the
similar to HashSet. elements after each
But slightly in the insertion and removal
slower side as it also operations.
maintains LinkedList
internally to maintain
the insertion order of
elements.
Insertion, Removal HashSet gives LinkedHashSet also TreeSet gives
And Retrieval performance of gives performance of performance of order
Operations order O(1) for order O(1) for O(log(n)) for
insertion, removal insertion, removal insertion, removal and
and retrieval and retrieval retrieval operations.
operations. operations.
How they compare HashSet uses LinkedHashSet also TreeSet uses
the elements? equals() and uses equals() and compare() or
hashCode() hashCode() methods compareTo() methods
methods to to compare the to compare the
compare the elements. elements and thus
elements and thus removing the possible
removing the duplicate elements. It
possible duplicate doesn’t use equals()
elements. and hashCode()
methods for
comparision of
elements.
Null elements HashSet allows LinkedHashSet also TreeSet doesn’t allow
maximum one null allows maximum one even a single null
element. null element. element. If you try to
insert null element
into TreeSet, it throws
NullPointerException.
Memory HashSet requires LinkedHashSet TreeSet also requires
Occupation less memory than requires more more memory than
LinkedHashSet and memory than HashSet HashSet as it also
TreeSet as it uses as it also maintains maintains Comparator
only HashMap LinkedList along with to sort the elements
internally to store HashMap to store its along with the
its elements. elements. TreeMap.
When To Use? Use HashSet if you Use LinkedHashSet if Use TreeSet if you
don’t want to you want to maintain want to sort the
maintain any order insertion order of elements according to
of elements. elements. some Comparator.

Question: Similarities between HashSet, LinkedHashSet and TreeSet.

Answer: All three doesn’t allow duplicate elements. All three are not synchronized. All
three are Cloneable and Serializable. Iterator returned by all three is fail-fast in nature. i.e
You will get ConcurrentModificationException if they are modified after the creation of
Iterator object.

Question: What is abstract class in java? What is abstraction? What is the


difference between abstract class and interface? Why we use abstract class while we
do the same work by using a normal class?
Answer: A class that is declared with abstract keyword is known as abstract class in java.
It can have abstract and non-abstract methods (method with body). It needs to be
extended and its method implemented. It cannot be instantiated.

Abstraction is a process of hiding the implementation details and showing only


functionality to the user. Another way, it shows only important things to the user and
hides the internal details for example sending SMS, you just type the text and send the
message. You don't know the internal processing about the message delivery. Abstraction
lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated. But there are many
differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods.
2) Abstract class doesn't support Interface supports multiple inheritances.
multiple inheritances.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
4) Abstract class can have static Interface can't have static methods, main
methods, main method and method or constructor.
constructor.
5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

The purpose of abstract classes is to function as base classes which can be extended by
subclasses to create a full implementation. The non abstract class can do same function as
abstract class but in this case we would not be able to enforce those common or
generalized behaviors (methods) which belong to that abstract class specifically. For
example, suppose there is an abstract animal class and it has common behaviors
(methods) such as eat() and sleep(). We want these two methods must be used by animal
subclasses. In this situation, non abstract class fails to implement this scenario. That’s
why the reason we use abstract class in java where we encounters this situation.

Question: What is volatile keyword in java?

Answer: volatile keyword prevents caching of variables. If you declare a variable as


volatile, then it will not be stored in the local cache. Whenever threads are updating the
values, it is updated to the main memory. So, other threads can access the updated value.

Volatile  Guarantees visibility and NOT atomicity

Synchronization (Locking)  Guarantees visibility and atomicity (if done properly)

Volatile is not a substitute for synchronization. Use volatile only when you are updating
the reference and not performing some other operations on it. Synchronized block can be
used in place of volatile but the inverse is not true. You can use volatile variables only
when all the following criteria are met:

 Writes to the variable do not depend on its current value, or you can ensure that only a
single thread ever updates the value.
 The variable does not participate in invariants with other state variables.
 Locking is not required for any other reason while the variable is being accessed.

The main differences between synchronized and volatile are:

 A primitive variable may be declared volatile (whereas you can't synchronize on a


primitive with synchronized).
 An access to a volatile variable never has the potential to block: we're only ever doing
a simple read or write, so unlike a synchronized block we will never holding on to any
lock.
 Because accessing a volatile variable never holds a lock, it is not suitable for cases
where we want to read-update-write as an atomic operation (unless we're prepared to
"miss an update").
 A volatile variable that is an object reference may be null (because you're effectively
synchronizing on the reference, not the actual object).

Attempting to synchronize on a null object will throw a NullPointerException.

You might also like