Java Interview Questions
Java Interview Questions
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.
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.
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.
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.
If the overridden method is has default access, then the overriding one must be
default, 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 #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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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 patterns provide solution for the better interaction between objects and how to
provide lose coupling and flexibility to extend easily.
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.
Mediator Pattern
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 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 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
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
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.
History
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.
Example: Make a class deal with lookups and exception, acting as a representative of the
client components.
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.
Definition: Adapt a uniform interface to access multiple databases like relational, un-
relational, object-oriented, etc.
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
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
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.
Example
To create a basic filter, you need to:
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.
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.
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.
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:
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.
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.
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
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
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).
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.
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: 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.
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:
class Loan{
private double interest;
private String type;
public Loan(){
this(“personal loan”);
}
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:
6) You can call methods of class by using this keyword as shown in below example.
7) this can be used to return object. this is a valid return value. Here is an example of
using as return value.
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:
This is the code for the hash function (also known as hashCode method) in Object Class:
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
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
, 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.
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 .
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);
}
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.
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.
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: 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.
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.
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. }
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. }
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.
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.
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.
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.
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.
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.