Frequently asked Java interview questions and answers – Part I

Frequently asked Java interview questions for experience of 2 to 5 years – Part I

Here we will see some of the frequently asked Java interview questions for an experience level of 2-5 years. I will also provide answers for these questions. I have faced all these questions in my interviews. It is important that you master the answer for these questions before attending any Java interview. Since there are more number of questions, I will discuss it in series of posts.

1. What are the OOP concepts in Java?

From this question, the interviewer will test your understanding of basics of Java. Java is an Object oriented programming language. In order to call Java as an OOP language, it should support OOP principles. Hence it is important to know what are the OOP concepts and how it is implemented in Java. There are four main OOP principles in Java. They are,

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

You can read more about these principles here,

Object-Oriented Programming Concepts

OOPs concepts in Java

2. Difference between an interface and an abstract class

An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods inside an interface are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Note: Java 8 introduces a new concept of default method implementation in interfaces. More on this here, default methods.

3. Difference between ArrayList and vector

ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add (), get (int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

4. Difference between HashMap and HashTable

This is an important question asked in many of the Java interviews.

HashMapHashTable
HashMap is not thread-safe. Since HashMap is not synchronized it performs better than Hashtable. Java 5 introduces ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.Methods in HashTable are synchronized. So it is thread-safe
Allows one null key and any number of null values.Does not permit null key and null values.
Iterator can be used to iterate keys and values of HashMapIterator or enumerator can be used for iteration
Iterator in the HashMap is  a fail-fast iterator and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method.The enumerator for the Hashtable is not fail-fast.
HashMap is much faster than HashtableBecause of thread-safety and synchronization Hashtable is much slower than HashMap

5.What are checked and unchecked exceptions? Give an example?

Refer to my previous post Exception handling in Java.

6. Explain the life cycle of a Servlet.

This is an important question to know your understanding of Servlets.

Consider the below diagram which involves typical use case for servlet life cycle.servlet life cycle

The following is a typical user scenario involving life cycle methods of servlet.

  1. Assume that a user requests to visit a URL.
    ->The browser then generates an HTTP request for this URL.
    ->This request is then sent to the appropriate server.
  1. The HTTP request is received by the web server and forwarded to the servlet container.
    ->The container maps this request to a particular servlet.
    ->The servlet is dynamically retrieved and loaded into the address space of the container.
  1. The container invokes the init() method of the servlet.
    ->This method is invoked only when the servlet is first loaded into memory.
    ->It is possible to pass initialization parameters to the servlet so that it may configure itself.
  1. The container invokes the service () method of the servlet.
    ->This method is called to process the HTTP request.
    ->The servlet may read data that has been provided in the HTTP request.
    ->The servlet may also formulate an HTTP response for the client.
  1. The servlet remains in the container’s address space and is available to process any other HTTP requests received from clients.
    ->The service () method is called for each HTTP request.
  1. The container may, at some point, decide to unload the servlet from its memory.
    ->The algorithms by which this decision is made are specific to each container.
  1. The container calls the servlet’s destroy () method to relinquish any resources such as file handles that are allocated for the servlet; important data may be saved to a persistent store.
  2. The memory allocated for the servlet and its objects can then be garbage collected.

To know more about this Servlet Lifecycle.

7. What is the difference between RequestDispatcher.Forward() and response.SendRedirect().

This is one more question to assess your knowledge in servlets.

Forward()SendRediret()
When we use forward method, request is transfer to other resource within the same server for further processing.In case of sendRedirect, request is transfer to another resource to different domain or different server for further processing.
In case of forward, Web container handle all process internally and client or browser is not involved.When you use SendRedirect, container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our requestIn case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
Visually we are not able to see the forwarded address, it is hidden.In address bar we are able to see the new redirected address it is transparent.
Using forward () method is faster then send redirect.SendRedirect is slower because one extra round trip is required because completely new request is created and old request object is lost. Two browser requests are required.
When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available.But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.
Example:
When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available.
Example:
Any kind of online payment when we use, merchant site will redirect us to net banking site which is completely new request, it process our request and again redirect to merchant site.

8.Explain compile time and runtime polymorphism in java. Give example.

Let us consider the following Vehicle, Car and Truck class.

A Vehicle can be driven, so is a Car and Truck. But in addition to this a Truck can also be loaded with goods. Let us create instances of these classes and drive() them and try to also load() the truck.

And the output is:

1.Driving vehicle …

2.Driving car…

3.Driving truck…

4.Loading truck…

 

Had the runtime polymorphism not kicked in, the output would have been: Driving vehicle … for all the three invocations of drive() method. You can also see that truckVehicle.load() results in a compile time error. So what’s happening in the above code?

Any object declaration and instantiation has 2 parts in it – The type of the reference and the type of the object created. For example in Vehicle carVehicle = new Car() the reference type is Vehicle and the object created is of type Car. Such an assignment is only possible when the object created type is a subclass of the reference type i.e in cases where inheritance is used.

Each object reference can be used to invoke methods and the methods which can be invoked is decided based on the reference type. And this is decided during the compile time. But the implementation to be invoked is decided based on the type of the object created. In the above example: carVehicle.drive() compiles because the drive() method is part of the Vehicle class and gives “Driving car…” as the output because the method is overridden by the Car class.

On similar lines: truckVehicle.load() gives compile time error because the method load() is not part of the Vehicle class, but is defined only in the Truck class. But the truck.load() compiles because the reference type is Truck class and the compiler can resolve the load() method.

To summarise:

  • The method binding happens at the compile time i.e which methods can be invoked on a given reference type is decided at the compile time.
  • The selection of the method’s implementation to execute happens at the run time i.e which implementation of the method to be executed i.e the super class version or one of the subclass’s version is decided at the run time and this is what leads to the runtime polymorphism.

9. Explain the life cycle of a Thread.

When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. By invoking start() method, it doesn’t mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed.

Different states of a thread are:

thread life cycle

More on this – Thread life cycle.

10. Difference between equals () and hashCode() method and when do you override it and explain the practical use of overriding it.

Read my previous post equals () and hashCode().

Hope you found this post useful.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
One comment

Add Comment

Required fields are marked *. Your email address will not be published.