In this part of Java Interview Questions , Here am going to present some of the important Java Interview Questions and its Answers which will help you in the interview process.
We have compiled a list of top Java interview questions which are classified into 7 sections, we will go through each one of them in the following sequence:
Being a Java professional, it is recommended to know the right interview question
let’s get started with the some set of basic Java Interview Questions.
Basic Java Interview Questions
Q1. Explain JDK, JVM and JRE ?
JVM (Java Virtual Machine): It is an abstract machine. It is a specification that provides run-time environment in which java bytecode can be executed. It follows three notations:
- Specification: It is a document that describes the implementation of the Java virtual machine. It is provided by Sun and other companies.
- Implementation: It is a program that meets the requirements of JVM specification.
- Runtime Instance: An instance of JVM is created whenever you write a java command on the command prompt and run the class.
JRE (Java Runtime Environment) : JRE refers to a runtime environment in which java bytecode can be executed. It implements the JVM (Java Virtual Machine) and provides all the class libraries and other support files that JVM uses at runtime. So JRE is a software package that contains what is required to run a Java program. Basically, it’s an implementation of the JVM which physically exists.
JDK(Java Development Kit) : It is the tool necessary to compile, document and package Java programs. The JDK completely includes JRE which contains tools for Java programmers. The Java Development Kit is provided free of charge. Along with JRE, it includes an interpreter/loader, a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development. In short, it contains JRE + development tools.
Q2. Explain about public static void main(String args).
static : It is a keyword in java which identifies it is class based i.e it can be accessed without creating the instance of a Class.
void : It is the return type of the method. Void defines the method which will not return any value.
main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
String args : It is the parameter passed to the main method.
Q3. Why Java is called platform independent?
Platform independent practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.
Q4. Why java is not 100% Object-oriented?
Java is not 100% Object-oriented because it makes use of eight primitive datatypes such as boolean, byte, char, int, float, double, long, short which are not objects.
Q5. What are wrapper classes?
Wrapper classes converts the java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.
Q6. What is constructor in Java?
In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.
There are two types of constructors:
- Default constructor
- Parameterized constructor
Q7. What is singleton class and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.
Q8. What is the difference between Array list and vector?
|Array List is not synchronized.||Vector is synchronized.|
|Array List is fast as it’s non-synchronized.||Vector is slow as it is thread safe.|
|If an element is inserted into the Array List, it increases its Array size by 50%.||Vector defaults to doubling size of its array.|
|Array List does not define the increment size.||Vector defines the increment size.|
|Array List can only use Iterator for traversing an Array List.||Except Hashtable, Vector is the only other class which uses both Enumeration and Iterator.|
Q9. What is the difference between equals() and == ?
Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.
“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.
Q10. What are the differences between Heap and Stack Memory?
The major difference between Heap and Stack memory are:
|Memory||Stack memory is used only by one thread of execution.||Heap memory is used by all the parts of the application.|
|Access||Stack memory can’t be accessed by other threads.||Objects stored in the heap are globally accessible.|
|Memory Management||Follows LIFO manner to free memory.||Memory management is based on generation associated to each object.|
|Lifetime||Exists until the end of execution of the thread.||Heap memory lives from the start till the end of application execution.|
|Usage||Stack memory only contains local primitive and reference variables to objects in heap space.||Whenever an object is created, it’s always stored in the Heap space.|
OOPS Java Interview Questions:
Q1. What is Polymorphism?
Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism:
- Compile time polymorphism
- Run time polymorphism
Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.
Q2. What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.
Q3. What is the difference between abstract classes and interfaces?
|An abstract class can provide complete, default code and/or just the details that have to be overridden.||An interface cannot provide any code at all,just the signature.|
|In case of abstract class, a class may extend only one abstract class.||A Class may implement several interfaces.|
|An abstract class can have non-abstract methods.||All methods of an Interface are abstract.|
|An abstract class can have instance variables.||An Interface cannot have instance variables|
|An abstract class can have any visibility: public, private, protected.||An Interface visibility must be public (or) none.|
|If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly||If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method|
|An abstract class can contain constructors||An Interface cannot contain constructors|
|Abstract classes are fast||Interfaces are slow as it requires extra indirection to find corresponding method in the actual class|
Q4. What is method overloading and method overriding?
Method Overloading :
- In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order.
- Method Overloading is to “add” or “extend” more to method’s behavior.
- It is a compile time polymorphism.
- The methods must have different signature.
- It may or may not need inheritance in Method Overloading.
Let’s take a look at the example below to understand it better.
- In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.
- Method Overriding is to “Change” existing behavior of method.
- It is a run time polymorphism.
- The methods must have same signature.
- It always requires inheritance in Method Overriding.
Let’s take a look at the example below to understand it better.
Q5. Can you override a private or static method in Java?
You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in sub class because it’s not accessible there. What you can do is create another private method with the same name in the child class. Let’s take a look at the example below to understand it better.
Q6. What is multiple inheritance? Is it supported by Java?
If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not allow to extend multiple classes.
The problem with multiple inheritance is that if multiple parent classes have a same method name, then at runtime it becomes difficult for the compiler to decide which method to execute from the child class.
Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred as Diamond Problem.
Q7. What is association?
Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. These relationship can be one to one, One to many, many to one and many to many.
Q8. What do you mean by aggregation?
Aggregation is a specialized form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy.
Q9. What is composition in Java?
Composition is again specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete.
Servlets Interview Questions
Q1. What is a servlet?
- Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
- The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
- All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
- Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class.
Q2. What are the differences between Get and Post methods?
|Limited amount of data can be sent because data is sent in header.||Large amount of data can be sent because data is sent in body.|
|Not Secured because data is exposed in URL bar.||Secured because data is not exposed in URL bar.|
|Can be bookmarked||Cannot be bookmarked|
|It is more efficient and used than Post||It is less efficient and used|
Q3. What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response.
There are two methods defined in this interface:
Q4. What are the differences between forward() method and sendRedirect() methods?
|Forward() method||SendRedirect() method|
|forward() sends the same request to another resource.||sendRedirect() method sends new request always because it uses the URL bar of the browser.|
|forward() method works at server side.||sendRedirect() method works at client side.|
|forward() method works within the server only.||sendRedirect() method works within and outside the server.|
Q5. What is the life-cycle of a servlet?
There are 5 stages in the lifecycle of a servlet:
- Servlet is loaded
- Servlet is instantiated
- Servlet is initialized
- Service the request
- Servlet is destroyed
Q6. How does cookies work in Servlets?
- Cookies are text data sent by server to the client and it gets saved at the client local machine.
- Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
- HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
- Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.
Q7. What are the differences between ServletContext vs ServletConfig?
The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.
|Servlet config object represent single servlet||It represent whole web application running on particular JVM and common for all the servlet|
|Its like local parameter associated with particular servlet||Its like global parameter associated with whole application|
|It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope||ServletContext has application wide scope so define outside of servlet tag in web.xml file.|
|getServletConfig() method is used to get the config object||getServletContext() method is used to get the context object.|
|for example shopping cart of a user is a specific to particular user so here we can use servlet config||To get the MIME type of a file or application session related information is stored using servlet context object.|
Q8. What are the different methods of session management in servlets?
Session is a conversational state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.
Some of the common ways of session management in servlets are:
- User Authentication
- HTML Hidden Field
- URL Rewriting
- Session Management API
JDBC Interview Questions
Q1. What is JDBC Driver?
JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:
- JDBC-ODBC bridge driver
- Native-API driver (partially java driver)
- Network Protocol driver (fully java driver)
- Thin driver (fully java driver)
Q2. What are the steps to connect to a database in java?
- Registering the driver class
- Creating connection
- Creating statement
- Executing queries
- Closing connection
Q3. What are the JDBC API components?
The java.sql package contains interfaces and classes for JDBC API.
- CallableStatement etc.
- SQLException etc.
Q4. What is the role of JDBC DriverManager class?
The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.
Q5. What is JDBC Connection interface?
The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.
Q6. What is the purpose of JDBC ResultSet interface?
The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.
Q7. What is JDBC ResultSetMetaData interface?
The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.
Q8. What is JDBC DatabaseMetaData interface?
The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.
Q9. What do you mean by batch processing in JDBC?
Batch processing helps you to group related SQL statements into a batch and execute them instead of executing a single query. By using batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.
Q10. What is the difference between execute, executeQuery, executeUpdate?
Statement execute(String query) is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as running Insert or Update queries. We can use getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update count.
Statement executeQuery(String query) is used to execute Select queries and returns the ResultSet. ResultSet returned is never null even if there are no records matching the query. When executing select queries we should use executeQuery method so that if someone tries to execute insert/update statement it will throw java.sql.SQLException with message “executeQuery method can not be used for update”.
Statement executeUpdate(String query) is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0.
We will be coming with more Question ….. stay tuned