51 Java Interview Questions and Answers

Dear Readers, Welcome to Java Interview questions with answers and explanation. These 51 solved Java questions will help you prepare for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

After reading these tricky Java questions, you can easily attempt the objective type and multiple choice type questions on Java.

Explain how to force the garbage collection in Java.(Java Interview Q & A)

- First of all Garbage collection is an automatic process and can't be forced. Although, you can request it by calling System.gc().
- JVM does not guarantee that GC will be started immediately.
- Every class inherits finalize() method from java.lang.Object.
- The finalize() method is called by garbage collector when it determines no more references to the object exists.
- You can sent request to recycle the unused objects by calling System.gc() and Runtime.gc() , but there is no guarantee when all the objects will garbage collected.

Advantages and disadvantages of Java Sockets.

Advantages of Java Sockets :

- Sockets are flexible and easy to implemented for general communications.
- Sockets cause low network traffic unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request.

Disadvantages of Java Sockets :

- Socket based communications allows only to send packets of raw data between applications.
- Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Java Interview questions and answers Video

What do you understand by Synchronization? why is it important?

- Synchronization is a process of controlling the access of shared resources by the multiple threads.

- It allows only one thread can access one resource at a time.

- It ensures one thread not to modify a shared object while another thread is in the process of using or updating the object's value.

- This often leads to significant errors. Synchronization prevents such type of data corruption.

Synchronizing a function :
public synchronized void SyncMet()
{
// Appropriate method-related code.
}

Constructors and normal methods.

- Constructors must have the same name as the class.
- Constructors can not return a value.
- Normal methods are only called once while regular methods can be called many times
- Normal methods can return a value or can be void.

What is an immutable class? How to create an immutable class?

- Immutable class is a class which once created, it’s contents can not be changed.
- Immutable objects are the objects whose state can not be changed once constructed.
- Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
- Immutable objects are automatically thread-safe since the state of the immutable objects can not be changed once they are created
- All wrapper classes in java.lang are immutable, i.e. String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

Difference between ArrayList and vector.

- ArrayList is not thread-safe whereas Vector is thread-safe.
- In Vector class each method is surrounded with a synchronized block and thus making Vector class thread-safe.
- 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.

What is the difference between Java and C++?

- Java is compatible with C++ but the backward compatibility is not being given in the case of C++.
- Java format is influenced by C++ only and it is strongly typed language but C++ is loosely typed language.
- C++ provides write once and compile anywhere concept, but Java provides write once run anywhere concept.
- C++ allows procedural, functional, object oriented and template programming, whereas java provides only object oriented paradigm.
- C++ calls directly to the system libraries for program, but java has to call through an interface to access the java libraries.
- C++ supports pointer, but there is no concept of pointers in Java language.

What is a java object and java application?

- Java object is an object that is provided by the execution of an application. When an application is compiled an object of that application is being made. Java application on the other hand is a program that is being written in Java and being read by the Java virtual machine.

What is the difference between multitasking and multithreading?

Multitasking includes two ways for representation :

1. Preemptive multitasking: where the system terminates the idle process without asking the user. For example: Unix/Linux, Windows NT
2. Non-preemptive multitasking: where the system ask the process to give the control to other process for execution. For example: Windows 3.1 and Mac OS 9.

Multithreading :

1. Multithreaded programs are the program that extend the functionality of the multitasking by dividing the program in thread and then execute the task as individual threads.
2. Threads run in a different area and each thread utilizes some amount of CPU and memory for execution.

What is the difference between multiple processes and multiple threads?

- Multiple processes are the way to provide multitasking environment to the user to allow him to switch over to different programs quickly. In these processes, it consists of complete set of its own variables and data. Multiple threads share the same variable and same data. Multiple processes are safe to use but multiple threads are riskier in the sense that they share the same data.

- Multiple processes have much more overhead but multiple threads have less overhead and individual threads can be stand alone if other threads are destroyed.

- In multiple processes inter communication is slower and more restrictive, whereas communication between threads are faster.

What is the requirement of thread in Java?

- Thread is the smallest execution unit for processing. A thread is a part of a process; it can exist within the same process or share the resources like memory. Java is a language which makes use of it in a better way as to execute the application in threads for faster output and using of fewer resources to execute the code.

What is the use of RUNNABLE interface?

- Runnable interface provide a thread pool through which you can execute large number of threads. This reduces the cost of creating and for garbage collection. It can be implemented by any class that has a thread which can be executed. The class includes a method run. Runnable is implemented by the class thread and can be made active or inactive. Runnable provides a way to make a class active without even sub-classing a thread. This can be done by instantiating a thread instance and passing itself as a target in the programming.

- For example :
class Animation extends JApplet
implements Runnable
{
. . .
public void run()
{
// thread action goes here
}
}

What are different types of states exist for a thread?

- There are four different types of states that exist for a thread and they are given below as:

1. New : This shows that a thread is new and ready to be acquired the processor and other resources.

2. Runnable : This state shows that the thread is either waiting or newly created and waiting for the resources to be given and make it Runnable.

3. Blocked : This state shows that a thread is blocked as there is some other thread which is using the resources.

4. Dead : This state shows that the thread is dead and terminated as it was being idle for a very long time.

What are the actions that can occur when a thread enters blocked state?

- The actions that get performed when a thread enters the blocked state are as follows:

1. A thread is in the blocked state due to the call of a sleep() method.
2. Thread calls an operation that requires the resource which is being used by some other thread in process.
3. A thread calls the method wait().
4. A Thread locks an object which is being associated with another thread.
5. suspend() method of the thread is called.

Why a dead thread occurs?

- Dead thread occurs due to two reasons:

1. A thread becomes dead when the function exits normally after execution.
2. A thread becomes dead due to some exception and then terminates itself.

- A thread can be dead by calling the kill or stop method. The method which is being called throws a thread-death error object which sends the message for the kill. To see that a thread is dead or not use isAlive method which returns true if the thread is runnable or blocked, in other cases it shows false.

On which platform J2EE is based?

- J2EE stands for Java 2 Enterprise Edition that provides a component based approach to design, development, assembly and deployment of enterprise applications. J2EE provides advanced features to be used by the user and it provides multithreading and multi-tired environment to support distributed application model. It also defines the unified security model and provides the support for integration of XML (Extensible Markup language), which is based on open standards and protocols.

What is the purpose of a web-client?

The main purpose of the web-client is to create dynamic web pages that consist of various types of markups like HTML, XML, and PHTML. It also generates the web components that are running on the web server. It allows the web browser to read and render the pages that are received from the server. It helps easy communication between the client and other clients that are connected to each other.

Is thin client different from web client?

No, a web client is also called as thin client. The main function of thin client is to provide data persistence and to have actual information processing. This is on the side where they clients share the resources between several users. Thin clients are not used for query purposes; execute business rules that are complex or connecting some applications. It is not used to perform heavy load operations.

What is the purpose of JSP and why it is widely used?

JSP stands for Java Server pages and it is used to create dynamic web pages. It is one of the widely used language for the creation of webpages. It allows the dynamic component to be added and it includes servlets that are used to execute dynamic codes. It is used to create static as well as dynamic content. It provides high level abstraction to the servlets.

How servlets are deployed in Java?

Servlets are Java classes that are used to store codes and create applications to be used by JSP for execution. These programs run on a web server and they are used to act as a middle layer, which takes the request and pass it to the server and gives the reply to the HTTP client. It is used to extend the capability of servers. They are used with HTTP protocol and to define the client server architecture. It is used to add the dynamic content to a webserver using the java run time libraries and java platform.

What are the jobs performed by servlets?

- Servlets are used for the web servers to receive and reply to the request that is sent by the user. The request comes from the HTTP client and the servlet code only delivers it to the HTTP server and brings back the reply and passes it to the client.

- The servlet includes the information and details about the browser, cookies, host name and other resources.

1. It is also used to generate the results by communicating with the database.
2. It allows the formatting to be done inside a document.
3. It sets the HTTP response parameter so that the browser will get to know what type of document is being returned.
4. It returns the reply to the client in the HTML format.

What are the advantages of servlets over traditional CGI?

- The advantages of servlets over traditional CGI are as follows:

1. Servlets are more efficient way to represent the data.

2. CGI creates an overhead on the process and execution time can be hindered.

3. Java Virtual Machine uses a lightweight java thread to handle the request, whereas CGI uses heavy weight operating system process.

4. The data loaded in the memory in the case of CGI program is heavier than the servlets. CGI program terminates after handling the request, whereas servlet remains in the memory and store the complex data between the requests.

5. Servlets are more convenient way to use the infrastructure and allow automatic parsing and decoding of HTML form data but it is not the case with CGI.

6. Servlets are more portable and secure and follow the standard API but CGI programs are executed by general purpose shells that are not very much secure.

What are advantages of JSP over ASP, PHP, Pure servlets and others?

- The advantages of JSP over ASP, PHP, Pure servlets and others are as follows:

1. JSP is written in java and it provides a powerful application platform that require reusable component. JSP is portable to web servers, whereas ASP is not.

2. JSP uses API for networking, database, distributed objects and servers, whereas PHP requires lots of understanding of APIs and learning a new language from start.

3. JSP allow user to separate presentation from the content and allow to set the dynamic content for use, whereas servlets are used only to code for the content which has to be presented.

4. JSP is used to provide dynamic information, whereas HTML doesn’t provide dynamic information.

What is the purpose of apache tomcat?

Apache server is a standalone server that is used to test servlets and create JSP pages. It is free and open source that is integrated in the Apache web server. It is fast, reliable server to configure the applications but it is hard to install. It is a servlet container that includes tools to configure and manage the server to run the applications. It can also be configured by editing XML configuration files.

Write a program to show the functionality of servlets.

- The servlets is being written like a normal application. The program is as follows:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet
{
   public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
   {
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       String docType =
       "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";
       out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello
       WWW</H1>\n" + "</BODY></HTML>");
   }
}
- This is the format of the servlet which is included in the JSP with the HTML tags and the output is being shown on the screen.

What is the life-cycle of servlets?

- The life cycle of servlet is as follows:

1. init Method :

init method is the initialization method and called when the servlet is first created. It is not called on each user request. It gets provoked when a user first invokes a URL corresponding to the servlet or when the server is started. The init methods also have different types:

i. init that takes no arguments.
public void init() throws ServletException
{
   // Initialization code...
}
ii. init that takes a ServletConfig
public void init(ServletConfig config)
throws ServletException
{
   super.init(config);
   // Initialization code...
}
2. Service Method

- When the server receives a request for a servlet a new thread is being made and a service is being called. This method checks the HTTP request type (get, post, etc) and calls output type like doget, do put, etc. The syntax is as follows:
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
   // Servlet Code
}
3. Destroy Method

- In this server decide to remove previously loaded servlet instance if it idle for a very long time. It calls the servlet’s destroy method to close all the database connections and perform the cleanup activities.

What is the purpose of HttpClient?

HttpClient is a class that is used for network communication by sending required request line and headers to the web server. It places the request lines in a text area until the communication get lost or the connection get closed. The connection can be closed if HttpClient gets interrupted by isInterrupted flag.

Why SocketUtil is used?

SocketUtil is a class that provides the utility to simplify the creation of streams that are used in network programming. This is used in NetworkClient and HttpClient. It contains the socket related functions. Its main function is to find unusued ports and to check that the ports are in use or not. It is also used to check the localhost address.

- The syntax can be:
isLocalhost
public static boolean isLocalhost(java.lang.String host)
- It checks the host name or IP address by looking for the local machine.

How the interruptible method gets implemented?

- Interruptible is an interface that is used to identify certain classes, which have an isInterrupted method.

- It is used by HttpClient to see the interruption done by any user or for the webclient.

- Its syntax is given as:
public interface Interruptible
{
   public boolean isInterrupted();
}

How to read request headers from servlets?

- Request headers are the headers which have been requested by the user and to read this a call of getHeader method is done by HttpServeltRequest to call the servlets.

- This also returns a string that specifies the header that is provided on the request otherwise it gives null. Header name can be written in any way and are not case sensitive.

- The syntax is as follows:
request.getHeader("Connection") or request.getHeader("connection")
- There is a method called getCookies that returns the content of the cookie header that is parsed and stored in an array of cookie objects.

Where pragma is used?

Pragma is used inside the servlets in the header with a certain value. The value is of no-cache that tells that a servlets is acting as a proxy and it has to forward request. Pragma directives allow the compiler to use the machine and operating system features while keeping the overall functionality with the Java language. These are different for different compilers.

What does adapter class provide?

- Adapter class provide to all methods an empty implementation in an event listener interface. These classes are useful in receiving and processing some of the events.

- A new event can be made listener by extending the adapter class.

- For Example :
includes MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved().

What is the difference between JDBC and ODBC?

1. ODBC stands for Open Database Connectivity which is used for databases that are proprietary like Microsoft database, whereas JDBC is used for Java applications.

2. JDBC can be directly used with java but ODBC can’t be directly used with Java because it has C interface.

3. JDBC doesn’t support pointers but ODBC does support it.

4. JDBC drivers are in-built and come with the Java installation but ODBC drivers has to be installed manually on all the client machines.

What are different core interfaces of Hibernate Framework?

- Hibernate applications interact with the applications that are being provided by Hibernate core:

1. org.hibernate.Session: this manages the operations of storing and retrieving the objects. It act as a persistent manager. It obtains its session from the session factory.

2. org.hibernate.SessionFactory: it is a heavy weight instance that creates one instance for overall application. If there are multiple databases then one instance is required per database.

3. org.hibernate.Criteria: it provides a way to do the search which is conditional over the resultset. Session factory contains criteria instances.

4. org.hibernate.Query: it is the representation of Hibernate query which is object oriented. It is being created by calling Session.createQuery().

What is dirty checking in Hibernate?

Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. Hibernate will compare objects by value, except for Collections, which are compared by identity.

What are the inheritance mapping models in Hibernate?

- Inheritance mapping models in Hibernate are of some importance as it allows the building of relationship between two classes.

- There are three kind of inheritance mapping models:

1. Table per concrete class with unions : This class will have all the common attributes duplicated with the same name and properties.

2. Table per class hierarchy : In this a class hierarchy will be mapped to a single table.

3. Table per subclass : It will consist of the table representation which will be independent from each other.

Explain the difference between abstraction and encapsulation.

- Abstraction solves the problem in the design side.

- Encapsulation is the Implementation.

- Abstraction focuses on the outside view of an object (i.e. the interface).

- Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.

- Encapsulation is the deliverables of Abstraction.

- Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

What is Dynamic Binding?

Dynamic binding (late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time.

What is an abstract class?

- Abstract class must be extended/subclassed.

- Abstract class serves as a template.

- A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

What is final?

- A final class can't be extended i.e., final class may not be subclassed.

- A final method can't be overridden when its class is inherited.

Difference between Vector and ArrayList.

Vector is synchronized whereas arraylist is not.

Explain the difference between Association, Aggregation and Inheritance relationships.

Association : It is a simplest relationship. The relation between customers and sales have a association relation

Aggregation :Account class is aggregation of voucher, cash and journal classes.

Inheritance :It is parent-child kind of relations. The relation between vehicle object and car object reflects perfect example of inheritance.

What is polymorphism in Java? What are the kinds of polymorphism?

- Polymorphism is the capability of an action or method to do different things based on the object acting upon.

- Two types of polymorphism:

1. Method polymorphism through overloading
2. Object polymorphism by inheritance and interface

What is Garbage collector?

Garbage collector is the process of automatically freeing objects that are no longer referenced by the program. It reduces a programmer's work from having to track when to free allocated memory. Java provides memory management through garbage collector.

Explain the importance of finalize() method.

- Finalize() method is fired when an object is just about to be reclaimed by the garbage collector. When an object needs to perform some action before the object is destroyed, Finalize() method is handy.

- Sometimes an object is holding some non-java resources that should be released before it is destroyed, finalization process of used.

Can we force the garbage collection to run?

- Yes, we force but it is not certain that garbage collector will act upon immediately.

- We can use, System.gc() or runtime.gc()

Explain the use of JAVAP tool.

- JavaP tool is used when the original source code is not available. It disassembles compiled java files.

What are Applets? What are sequences of events which occur in Applet?

- An Applet is an application that is accessed from a web server.

- An applet has limited access to the resources on the client, thus doesn't breach client's security.

- Applets are automatically installed and run from browser.

Sequence of events :

1. Init method is called when an applet is first loaded.

2. Start method is called when user visits a browser with an applet.

3. Paint() is called every time when applet has to re-display everything.

Which package consist an applet class?

- java.applet package

What are class loaders?

- It is the class that is responsible for finding and loading classes at runtime.

- There are 3 types of class loader:

1. Bootstrap class loader
2. Extension class loader
3. System class loader

Difference between standard Java Array and Arraylist class.

- Arraylist supports dynamic arrays that can grow depending on demand.
- Standard Java arrays are fixed length once they are created.

What is a TreeSet class?

- TreeSet class creates a collection that uses a tree for storage.

- It is used to store large amount of data

- Items in the collection are stored in ascending order.
Difference between Java and JavaScript
Java - difference between Java and JavaScript - Java is an Object Oriented Programming Language which is developed by Sun Microsystems. It is capable of running on multiple operating systems with the help of.....
How to obtain a performance profile of Java program
Java - performance profile in Java - To improve the performance of a program, performance analysis is used. The usual purpose of this analysis is to determine which sections of a program to optimize......
Why doesn't Java run on all platforms?
Java runs mostly on all platforms. For running a Java program we need JVM on all the platforms. If JVM is not installed on any platform than we are not able to run ...
Post your comment
Discussion Board
Java questions and answers
Good questions and answers. very helpful for interview preparations. I have an interview in cognizant and accenture in the coming week. Both test and questions and answers would be of great help. Thanks CareerRide!
Java interview 11-7-2017
core java
Hai Sir, I have doubt in java. And my doubt is why java is dynamic programming language. Can you explain my doubt with a logical example.

please sir ,clarify my doubt.
lavanya 07-8-2017
java programming papers pune university
Nice
kajal jadhav 04-18-2015
java interview Questions
Here's some more java questions:

1) Junior java developer
a) Basic ocjp (former scjp) questions:
– What does static, final mean, purposes;
– How many accesibility modifiers exist? Please describe them.
– Why do you need a main method?
– How many constructors can you have?
– Define overwriting and overloading
– Give java API implementations for overwriting and overloading
– Describe the String class – unique properties
– StringBuilder vs StringBuffer
– Collections : please describe, give some examples and compare them to eachother
– ArrayList vs Vector
– HashMap vs HashTable
– What’s a tree
– What’s a map
– Multithreading: describe the management in java
– What’s a semaphone?
– How many states are there for threads?
– Describe the usage for synchronized word (2)
– Serialization in java – a descrition and usage
– Garbage collection in java – description and usage
– Can you guarantee the garbage collection process?
b) Simple design pattern questions:
– Singleton please describe main features and coding
– Factory please describe main features and coding
– Have you used others? please describe them

2) Intermediate and Senior level – depending on rate of good responses, additional questions to 1):

http://centraladvisor.com/programming-2/java/java-developer-interview
Bogdan 08-1-2012
Java interview questions and answers
Explain the importance of DriverManager.

The basic service to manage set of JDBC drivers.


What are the methods in Object?

clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

Define a nested class.

If all the methods of a inner class is static then it is a nested class.

What is garbage collection?

Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process


Difference between LinkedList and ArrayList.

LinkedList are meant for sequential accessing.

ArrayList are meant for random accessing.


Define a package.

Packages provides wide namespace ability and allows to group set of classes into a single unit.
Raj 12-5-2011
Java interview questions and answers
Explain the significance of ListIterator.

Using ListIterator you can iterate back and forth.



Can you explain inner class.

If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.

Can you explain the meaning of aggregation and composition

Aggregation - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its

reference, then it is called aggregation.

Composition - Holding the reference of the other class within some other class is known as composition.

Is it possible to instantiate the Math class?

You can’t instantiate the math class.
Pankaj 12-5-2011
Java interview questions and answers
Define Locale.

A Locale object represents a specific geographical, political, or cultural region.

How will you load a specific locale?

By using ResourceBundle.getBundle(…);

Is JVM a compiler or an interpreter?

Interpreter





Can you explain the usages of Class.forName()?

It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).

Inq adds a question: Expain the reason for each keyword of

public static void main(String args[])

Akash 12-5-2011
Java interview questions and answers
Define reflection.

Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes.


Can you tell me range of byte?

128 to 127


How to invoke external process in Java.

Runtime.getRuntime().exec(….)




What is the best way to findout the time/memory consuming process?

By using profiler
Rakesh 12-5-2011