You are on page 1of 104

JAVA

equals() method 

In  java  equals()  method  is  used  to  compare  equality  of  two  Objects.  The  equality  can 

be compared in two ways: 

● Shallow comparison: The default implementation of equals method is 


defined in Java.lang.Object class which simply checks if two Object 
references (say x and y) refer to the same Object. i.e. It checks if x == y. 
Since Object class has no data members that define its state, it is also 
known as shallow comparison. 
● Deep Comparison: Suppose a class provides its own implementation of 
equals() method in order to compare the Objects of that class w.r.t state of 
the Objects. That means data members (i.e. fields) of Objects are to be 
compared with one another. Such Comparison based on data members is 
known as deep comparison. 

hashCode() method 

It  returns  the  hashcode  value  as  an  Integer. Hashcode value is mostly used in hashing 

based  collections  like  HashMap,  HashSet,  HashTable….etc.  This  method  must  be 

overridden in every class which overrides equals() method. 


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.

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:

Features Stack Heap

Memory Stack memory is used only by Heap memory is used by all the parts
one thread of execution. of the application.

Access Stack memory can’t be Objects stored in the heap are


accessed by other threads. globally accessible.
Memory Follows LIFO manner to free Memory management is based on
Manageme memory. generation associated to each
object.
nt

Lifetime Exists until the end of Heap memory lives from the start till
execution of the thread. the end of application execution.

Usage Stack memory only contains Whenever an object is created, it’s


local primitive and reference always stored in the Heap space.
variables to objects in heap
space.

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. Servlet API hierarchy is

shown in below image.


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. Servlet API hierarchy is

shown in below image.

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:

1.void forward()
2.void include()

SERVLET CYCLE

1. Servlet is loaded
2. Servlet is instantiated
3. Servlet is initialized
4. Service the request
5. Servlet is destroyed

​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:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. 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
Top 75 Java Interview Questions You
Must Prepare In 2018
Recommended by 521 users

Aayushi Johari

Published on Oct 18,2018

​ ​23 Comments

590.1K Views

Bookmark
Email Post

Java Interview Questions

In this Java Interview Questions blog, I am going to list some of the most important Java Interview

Questions and Answers which will set you apart in the interview process. Java is used by approx

10 Million developers worldwide to develop applications for 15 Billion devices supporting Java. It

is also used to create applications for trending technologies like Big Data to household devices

like Mobiles and DTH boxes. And hence today, Java is used everywhere!

We have compiled a list of top Java interview questions which are classified into 7 sections,

namely:

1. Basic Interview Questions


2. OOPs Interview questions
3. JDBC Interview questions
4. Spring Interview questions
5. Hibernate Interview questions
6. JSP Interview questions
7. Exception and thread Interview questions

Java Interview Questions and Answers | Edureka

As a Java professional, it is essential to know the right buzzwords, learn the right technologies

and prepare the right answers to commonly asked Java Interview Questions. Here’s a definitive

list of top Java Interview Questions that will guarantee a breeze-through to the next level.

In case you attended any Java interview recently, or have additional questions beyond what we

covered, we encourage you to post them in our ​QnA Forum​. Our expert team will get back to you

at the earliest.

So let’s get started with the first set of basic Java Interview Questions.

Basic Java Interview Questions

Q1. Explain JDK, JRE and JVM?

JDK JRE JVM

It stands for Java It stands for Java Runtime It stands for Java Virtual
Development Kit. Environment. Machine.
It is the tool JRE refers to a runtime It is an abstract machine. It is a
necessary to environment in which java specification that provides
compile, document bytecode can be executed. run-time environment in which
and package Java java bytecode can be executed.
programs.

Along with JRE, it It implements the JVM JVM follows three notations:
includes an (Java Virtual Machine) and Specification(document that
interpreter/loader, a provides all the class describes the implementation
compiler (javac), an libraries and other support of the Java virtual machine),
archiver (jar), a files that JVM uses at Implementation(program that
documentation runtime. So JRE is a meets the requirements of JVM
generator (javadoc) software package that specification) and Runtime
and other tools contains what is required Instance(instance of JVM is
needed in Java to run a Java program. created whenever you write a
development. In Basically, it’s an java command on the
short, it contains implementation of the JVM command prompt and run
JRE + development which physically exists. class).
tools.

Q2. Explain public static void main(String args[]).

● public : Public is an access modifier, which is used to specify who can access this

method. Public means that this Method will be accessible by any Class.

● 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 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 are constructors 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:

1. Default constructor
2. 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 Vector

Array List is not synchronized. Vector is synchronized.

Array List is fast as it’s Vector is slow as it is thread safe.


non-synchronized.

If an element is inserted into the Vector defaults to doubling size of its array.
Array List, it increases its Array size
by 50%.

Array List does not define the Vector defines the increment size.
increment size.

Array List can only use Iterator for Except Hashtable, Vector is the only other
traversing an Array List. 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.

1 public class Equaltest {

2 public static void main(String[] args) {

String str1= new String(“ABCD”);


3

String str2= new String(“ABCD”);


4

if(Str1 == str2)
5

{
6
System.out.println("String 1 == String 2 is true");
7
}

8
else

9
{

10
System.out.println("String 1 == String 2 is false");

11 String Str3 = Str2;

12 if( Str2 == Str3)

13 {
14 System.out.println("String 2 == String 3 is true");

15 }

else
16

{
17

System.out.println("String 2 == String 3 is false");


18

}
19
if(Str1.equals(str2))
20
{

21
System.out.println("String 1 equals string 2 is true");

22
}

23
else

24 {

25 System.out.prinltn("String 1 equals string 2 is false");

26 }

}}
27

28

29

Q10. What are the differences between Heap and Stack Memory?
The major difference between Heap and Stack memory are:

Features Stack Heap

Memory Stack memory is used only by Heap memory is used by all the parts
one thread of execution. of the application.

Access Stack memory can’t be accessed by Objects stored in the heap are
other threads.
globally accessible.

Memory Follows LIFO manner to free Memory management is based on


Manageme memory. generation associated to each
nt object.

Lifetime Exists until the end of Heap memory lives from the start till
execution of the thread. the end of application execution.

Usage Stack memory only contains Whenever an object is created, it’s


local primitive and reference always stored in the Heap space.
variables to objects in heap
space.

In case you are facing any challenges with these java interview questions, please comment your

problems in the section below.

Get Certified With Industry Level Projects & Fast Track Your Career​​Take A Look!
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:

1. Compile time polymorphism


2. 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.

1 class Car {

2 void run()

{
3

System.out.println(“car is running”);
4

}
5

}
6
class Audi extends Car {
7
void run()

8
{

9
System.out.prinltn(“Audi is running safely with 100km”);
10 }

11 public static void main(String args[])

{
12

Car b= new Audi();//upcasting


13

b.run();
14

}
15
}
16

17

Q3. What is the difference between abstract classes and


interfaces?

Abstract Class Interfaces

An abstract class can provide An interface cannot provide any code at


complete, default code and/or just the all,just the signature.
details that have to be overridden.

In case of abstract class, a class may A Class may implement several


extend only one abstract class. interfaces.

An abstract class can have All methods of an Interface are abstract.


non-abstract methods.
An abstract class can have instance An Interface cannot have instance
variables. variables

An abstract class can have any An Interface visibility must be public (or)
visibility: public, private, protected. none.

If we add a new method to an abstract If we add a new method to an Interface


class then we have the option of then we have to track down all the
providing default implementation and implementations of the interface and
therefore all the existing code might define implementation for the new
work properly method

An abstract class can contain An Interface cannot contain constructors


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.

1 class Adder {

2 Static int add(int a, int b)

{
3

return a+b;
4

}
5

Static double add( double a, double b)


6
{
7
return a+b;

8
}

9
public static void main(String args[])

10
{

11 System.out.println(Adder.add(11,11));

12 System.out.println(Adder.add(12.3,12.6));

13 }}

14

Method Overriding:
● 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.

1 class Car {

2 void run(){

System.out.println(“car is running”);
3

}
4

Class Audi extends Car{


5

void run()
6
{
7
System.out.prinltn(“Audi is running safely with 100km”);

8
}

9
public static void main( String args[])

10
{

11 Car b=new Audi();


12 b.run();

13 }

}
14

15

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.

1 class Base {

2 private static void display() {

System.out.println("Static or class method from Base");


3

}
4

public void print() {


5

System.out.println("Non-static or instance method from Base");


6
}
7
class Derived extends Base {

8
private static void display() {
9 System.out.println("Static or class method from Derived");

10 }

public void print() {


11

System.out.println("Non-static or instance method from Derived");


12

}
13

public class test {


14
public static void main(String args[])
15
{

16
Base obj= new Derived();

17
obj1.display();

18
obj1.print();

19 }

20 }

21

22

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.

In case you are facing any challenges with these java interview questions, please comment your

problems in the section below. Apart from this Java Interview Questions Blog, if you want to get

trained from professionals on this technology, you can opt for a structured training from edureka!

Learn Java From Experts


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. Servlet API hierarchy is shown in below image.
Q2. What are the differences between Get and Post methods?

Get Post

Limited amount of data can be sent Large amount of data can be sent
because data is sent in header. because data is sent in body.

Not Secured because data is exposed Secured because data is not exposed in
in URL bar. URL bar.

Can be bookmarked Cannot be bookmarked

Idempotent Non-Idempotent
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:

1.void forward()

2.void include()
Q4. What are the differences between forward() method and
sendRedirect() methods?

Forward() method SendRedirect() method

forward() sends the same request to sendRedirect() method sends new


another resource. 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 sendRedirect() method works within and
server only. outside the server.

Q5. What is the life-cycle of a servlet?


There are 5 stages in the lifecycle of a servlet:

1. Servlet is loaded
2. Servlet is instantiated
3. Servlet is initialized
4. Service the request
5. 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.

ServletConfig ServletContext

Servlet config object represent single It represent whole web application


servlet running on particular JVM and common
for all the servlet

Its like local parameter associated Its like global parameter associated with
with particular servlet whole application

It’s a name value pair defined inside ServletContext has application wide
the servlet section of web.xml file so it scope so define outside of servlet tag in
has servlet wide scope web.xml file.

getServletConfig() method is used to getServletContext() method is used to get


get the config object the context object.
for example shopping cart of a user is To get the MIME type of a file or
a specific to particular user so here application session related information is
we can use servlet config 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:

1. User Authentication
2. HTML Hidden Field
3. Cookies
4. URL Rewriting
5. Session Management API

In case you are facing any challenges with these java interview questions, please comment your

problems in the section below. Apart from this Java Interview Questions Blog, if you want to get
trained from professionals on this technology, you can opt for a structured training from edureka!

Click below to know more.

Get Java Certified

​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:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. 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.
Interfaces:

● Connection

● Statement

● PreparedStatement

● ResultSet

● ResultSetMetaData

● DatabaseMetaData

● CallableStatement etc.

Classes:

● DriverManager

● Blob

● Clob

● Types

● 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.

SPRING

Q3. List some of the important annotations in annotation-based


Spring configuration.
The important annotations are:

● @Required

● @Autowired

● @Qualifier

● @Resource

● @PostConstruct

● @PreDestroy

Top 75 Java Interview Questions You


Must Prepare In 2018
Recommended by 521 users
Aayushi Johari

Published on Oct 18,2018

​ ​23 Comments

590.1K Views

Bookmark

Email Post

Java Interview Questions

In this Java Interview Questions blog, I am going to list some of the most important Java Interview

Questions and Answers which will set you apart in the interview process. Java is used by approx
10 Million developers worldwide to develop applications for 15 Billion devices supporting Java. It

is also used to create applications for trending technologies like Big Data to household devices

like Mobiles and DTH boxes. And hence today, Java is used everywhere!

We have compiled a list of top Java interview questions which are classified into 7 sections,

namely:

1. Basic Interview Questions


2. OOPs Interview questions
3. JDBC Interview questions
4. Spring Interview questions
5. Hibernate Interview questions
6. JSP Interview questions
7. Exception and thread Interview questions

Java Interview Questions and Answers | Edureka


As a Java professional, it is essential to know the right buzzwords, learn the right technologies

and prepare the right answers to commonly asked Java Interview Questions. Here’s a definitive

list of top Java Interview Questions that will guarantee a breeze-through to the next level.

In case you attended any Java interview recently, or have additional questions beyond what we

covered, we encourage you to post them in our ​QnA Forum.​ Our expert team will get back to you

at the earliest.

So let’s get started with the first set of basic Java Interview Questions.

Basic Java Interview Questions

Q1. Explain JDK, JRE and JVM?

JDK JRE JVM

It stands for Java It stands for Java Runtime It stands for Java Virtual
Development Kit. Environment. Machine.

It is the tool JRE refers to a runtime It is an abstract machine. It is a


necessary to environment in which java specification that provides
compile, document bytecode can be executed. run-time environment in which
and package Java java bytecode can be executed.
programs.
Along with JRE, it It implements the JVM JVM follows three notations:
includes an (Java Virtual Machine) and Specification(document that
interpreter/loader, a provides all the class describes the implementation
compiler (javac), an libraries and other support of the Java virtual machine),
archiver (jar), a files that JVM uses at Implementation(program that
documentation runtime. So JRE is a meets the requirements of JVM
generator (javadoc) software package that specification) and Runtime
and other tools contains what is required Instance(instance of JVM is
needed in Java to run a Java program. created whenever you write a
development. In Basically, it’s an java command on the
short, it contains implementation of the JVM command prompt and run
JRE + development which physically exists. class).
tools.

Q2. Explain public static void main(String args[]).

● public : Public is an access modifier, which is used to specify who can access this

method. Public means that this Method will be accessible by any Class.

● 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 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 are constructors 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:

1. Default constructor
2. 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 Vector

Array List is not synchronized. Vector is synchronized.

Array List is fast as it’s Vector is slow as it is thread safe.


non-synchronized.

If an element is inserted into the Vector defaults to doubling size of its array.
Array List, it increases its Array size
by 50%.

Array List does not define the Vector defines the increment size.
increment size.

Array List can only use Iterator for Except Hashtable, Vector is the only other
traversing an Array List. 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.

1 public class Equaltest {

2 public static void main(String[] args) {

String str1= new String(“ABCD”);


3

String str2= new String(“ABCD”);


4

if(Str1 == str2)
5

{
6
System.out.println("String 1 == String 2 is true");
7
}

8
else

9
{

10
System.out.println("String 1 == String 2 is false");

11 String Str3 = Str2;

12 if( Str2 == Str3)

13 {
14 System.out.println("String 2 == String 3 is true");

15 }

else
16

{
17

System.out.println("String 2 == String 3 is false");


18

}
19
if(Str1.equals(str2))
20
{

21
System.out.println("String 1 equals string 2 is true");

22
}

23
else

24 {

25 System.out.prinltn("String 1 equals string 2 is false");

26 }

}}
27

28

29

Q10. What are the differences between Heap and Stack Memory?
The major difference between Heap and Stack memory are:

Features Stack Heap

Memory Stack memory is used only by Heap memory is used by all the parts
one thread of execution. of the application.

Access Stack memory can’t be accessed by Objects stored in the heap are
other threads.
globally accessible.

Memory Follows LIFO manner to free Memory management is based on


Manageme memory. generation associated to each
nt object.

Lifetime Exists until the end of Heap memory lives from the start till
execution of the thread. the end of application execution.

Usage Stack memory only contains Whenever an object is created, it’s


local primitive and reference always stored in the Heap space.
variables to objects in heap
space.

In case you are facing any challenges with these java interview questions, please comment your

problems in the section below.

Get Certified With Industry Level Projects & Fast Track Your Career​​Take A Look!
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:

1. Compile time polymorphism


2. 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.

1 class Car {

2 void run()

{
3

System.out.println(“car is running”);
4

}
5

}
6
class Audi extends Car {
7
void run()

8
{

9
System.out.prinltn(“Audi is running safely with 100km”);
10 }

11 public static void main(String args[])

{
12

Car b= new Audi();//upcasting


13

b.run();
14

}
15
}
16

17

Q3. What is the difference between abstract classes and


interfaces?

Abstract Class Interfaces

An abstract class can provide An interface cannot provide any code at


complete, default code and/or just the all,just the signature.
details that have to be overridden.

In case of abstract class, a class may A Class may implement several


extend only one abstract class. interfaces.

An abstract class can have All methods of an Interface are abstract.


non-abstract methods.
An abstract class can have instance An Interface cannot have instance
variables. variables

An abstract class can have any An Interface visibility must be public (or)
visibility: public, private, protected. none.

If we add a new method to an abstract If we add a new method to an Interface


class then we have the option of then we have to track down all the
providing default implementation and implementations of the interface and
therefore all the existing code might define implementation for the new
work properly method

An abstract class can contain An Interface cannot contain constructors


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.

1 class Adder {

2 Static int add(int a, int b)

{
3

return a+b;
4

}
5

Static double add( double a, double b)


6
{
7
return a+b;

8
}

9
public static void main(String args[])

10
{

11 System.out.println(Adder.add(11,11));

12 System.out.println(Adder.add(12.3,12.6));

13 }}

14

Method Overriding:
● 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.

1 class Car {

2 void run(){

System.out.println(“car is running”);
3

}
4

Class Audi extends Car{


5

void run()
6
{
7
System.out.prinltn(“Audi is running safely with 100km”);

8
}

9
public static void main( String args[])

10
{

11 Car b=new Audi();


12 b.run();

13 }

}
14

15

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.

1 class Base {

2 private static void display() {

System.out.println("Static or class method from Base");


3

}
4

public void print() {


5

System.out.println("Non-static or instance method from Base");


6
}
7
class Derived extends Base {

8
private static void display() {
9 System.out.println("Static or class method from Derived");

10 }

public void print() {


11

System.out.println("Non-static or instance method from Derived");


12

}
13

public class test {


14
public static void main(String args[])
15
{

16
Base obj= new Derived();

17
obj1.display();

18
obj1.print();

19 }

20 }

21

22

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.

In case you are facing any challenges with these java interview questions, please comment your

problems in the section below. Apart from this Java Interview Questions Blog, if you want to get

trained from professionals on this technology, you can opt for a structured training from edureka!

Learn Java From Experts


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. Servlet API hierarchy is shown in below image.
Q2. What are the differences between Get and Post methods?

Get Post

Limited amount of data can be sent Large amount of data can be sent
because data is sent in header. because data is sent in body.

Not Secured because data is exposed Secured because data is not exposed in
in URL bar. URL bar.

Can be bookmarked Cannot be bookmarked

Idempotent Non-Idempotent
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:

1.void forward()

2.void include()
Q4. What are the differences between forward() method and
sendRedirect() methods?

Forward() method SendRedirect() method

forward() sends the same request to sendRedirect() method sends new


another resource. 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 sendRedirect() method works within and
server only. outside the server.

Q5. What is the life-cycle of a servlet?


There are 5 stages in the lifecycle of a servlet:

1. Servlet is loaded
2. Servlet is instantiated
3. Servlet is initialized
4. Service the request
5. 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.

ServletConfig ServletContext

Servlet config object represent single It represent whole web application


servlet running on particular JVM and common
for all the servlet

Its like local parameter associated Its like global parameter associated with
with particular servlet whole application

It’s a name value pair defined inside ServletContext has application wide
the servlet section of web.xml file so it scope so define outside of servlet tag in
has servlet wide scope web.xml file.

getServletConfig() method is used to getServletContext() method is used to get


get the config object the context object.
for example shopping cart of a user is To get the MIME type of a file or
a specific to particular user so here application session related information is
we can use servlet config 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:

1. User Authentication
2. HTML Hidden Field
3. Cookies
4. URL Rewriting
5. Session Management API

In case you are facing any challenges with these java interview questions, please comment your

problems in the section below. Apart from this Java Interview Questions Blog, if you want to get
trained from professionals on this technology, you can opt for a structured training from edureka!

Click below to know more.

Get Java Certified

​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:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. 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.
Interfaces:

● Connection

● Statement

● PreparedStatement

● ResultSet

● ResultSetMetaData

● DatabaseMetaData

● CallableStatement etc.

Classes:

● DriverManager

● Blob

● Clob

● Types

● 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.

You should use execute() method only when you are not sure about the type of statement else use

executeQuery or executeUpdate method.


Q4. What purpose does the keywords final, finally, and finalize
fulfill?
Final:
Final is used to apply restrictions on class, method and variable. Final class can’t

be inherited, final method can’t be overridden and final variable value can’t be

changed. Let’s take a look at the example below to understand it better.

1
class FinalVarExample {

2 public static void main( String args[])

{
3

final int a=10; // Final variable


4
a=50; //Error as value can't be changed

5
}

Finally
Finally is used to place important code, it will be executed whether exception is

handled or not. Let’s take a look at the example below to understand it better.
1
class FinallyExample {

2 public static void main(String args[]){

try {
3

int x=100;
4
}

5
catch(Exception e) {

6 System.out.println(e);

}
7

finally {
8
System.out.println("finally block is executing");}

9
}}

10 }

11
12

Finalize
Finalize is used to perform clean up processing just before object is garbage

collected. Let’s take a look at the example below to understand it better.

1
class FinalizeExample {

2 public void finalize() {

System.out.println("Finalize is called");
3

}
4
public static void main(String args[])

5
{

6 FinalizeExample f1=new FinalizeExample();

FinalizeExample f2=new FinalizeExample();


7

f1= NULL;
8
f2=NULL;

9
System.gc();
10
}

11 }

12

13

​Q5. What are the differences between throw and throws?


throw keyword throws keyword

Throw is used to explicitly throw Throws is used to declare an exception.

an exception.

Checked exceptions can not be Checked exception can be propagated with


propagated with throw only. throws.

Throw is followed by an instance. Throws is followed by class.


Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple You can declare multiple exception e.g.
exception public void method()throws
IOException,SQLException.

Q11. What is synchronization?


Synchronization refers to multi-threading. A synchronized block of code can be

executed by only one thread at a time. As Java supports execution of multiple

threads, two or more threads may access the same fields or objects.

Synchronization is a process which keeps all concurrent threads in execution to

be in sync. Synchronization avoids memory consistency errors caused due to

inconsistent view of shared memory.

REST Interview Questions

What REST stands for?


REST stands for REpresentational State Transfer.

What is REST?
REST is web standards based architecture and uses HTTP Protocol for data communication. It
revolves around resource where every component is a resource and a resource is accessed by
a common interface using HTTP standard methods. REST was first introduced by Roy Fielding
in 2000.

In REST architecture, a REST Server simply provides access to resources and REST client
accesses and presents the resources. Here each resource is identified by URIs/ global IDs.
REST uses various representations to represent a resource like text, JSON and XML. Now a
days JSON is the most popular format being used in web services.

Name some of the commonly used HTTP methods used in REST based architecture?
Following well known HTTP methods are commonly used in REST based architecture −

GET − Provides a read only access to a resource.

PUT − Used to create a new resource.

DELETE − Ued to remove a resource.

POST − Used to update a existing resource or create a new resource.

OPTIONS − Used to get the supported operations on a resource.

Which protocol is used by RESTful webservices?


RESTful web services make use of HTTP protocol as a medium of communication

between client and server.

What are the core components of a HTTP Request?


A HTTP Request has five major parts −

● Verb − Indicate HTTP methods such as GET, POST, DELETE, PUT etc.

● URI − Uniform Resource Identifier (URI) to identify the resource on server.

● HTTP Version − Indicate HTTP version, for example HTTP v1.1 .

● Request Header − Contains metadata for the HTTP Request message as

key-value pairs. For example, client ( or browser) type, format supported by

client, format of message body, cache settings etc.

● Request Body − Message content or Resource representation.

What are the core components of a HTTP response?


A HTTP Response has four major parts −

● Status/Response Code − Indicate Server status for the requested resource. For

example 404 means resource not found and 200 means response is ok.

● HTTP Version − Indicate HTTP version, for example HTTP v1.1 .

● Response Header − Contains metadata for the HTTP Response message as

key-value pairs. For example, content length, content type, response date,

server type etc.

● Response Body − Response message content or Resource representation.

What is URI?
URI stands for Uniform Resource Identifier. Each resource in REST architecture is
identified by its URI.

What is purpose of a URI in REST based webservices?

Purpose of an URI is to locate a resource(s) on the server hosting the web service.

What is format of a URI in REST architecture?


A URI is of following format −

<protocol>​://​<service-name>​/​<ResourceType>​/​<ResourceID>

What is the purpose of HTTP Verb in REST based webservices?


VERB identifies the operation to be performed on the resource

What do you mean by idempotent operation?

Idempotent operations means their result will always same no matter how many times
these operations are invoked.

Which type of Webservices methods are to be idempotent?

PUT and DELETE operations are idempotent.

Which type of Webservices methods are to be read only?

GET operations are read only and are safe.

What is the difference between PUT and POST operations?

PUT and POST operation are nearly same with the difference lying only in the result
where PUT operation is idempotent and POST operation can cause different result.

What should be the purpose of OPTIONS method of RESTful web services?

It should list down the supported operations in a web service and should be read only.

What do you mean by idempotent operation?

Idempotent operations means their result will always same no matter how many times
these operations are invoked.

Which type of Webservices methods are to be idempotent?

PUT and DELETE operations are idempotent.

Which type of Webservices methods are to be read only?

GET operations are read only and are safe.

What is the difference between PUT and POST operations?


PUT and POST operation are nearly same with the difference lying only in the result
where PUT operation is idempotent and POST operation can cause different result.

What should be the purpose of OPTIONS method of RESTful web services?

It should list down the supported operations in a web service and should be read only.

What is JAX-RS?
JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based

programming language API and specification to provide support for created RESTful

Webservices. Its 2.0 version was released in 24 May 2013. JAX-RS makes heavy use of

annotations available from Java SE 5 to simplify development of JAVA based web

services creation and deployment. It also provides supports for creating clients for

RESTful web services.

Learn from Professionals!

Spring Interview Questions

Q1. What is a Spring?

Wikipedia defines the Spring framework as “an application framework and inversion of control

container for the Java platform. The framework’s core features can be used by any Java

application, but there are extensions for building web applications on top of the Java EE

platform.” Spring is essentially a lightweight, integrated framework that can be used for

developing enterprise applications in java.

Q2. Name the different modules of the Spring framework.


Some of the important Spring Framework modules are:

● Spring Context – for dependency injection.

● Spring AOP – for aspect oriented programming.

● Spring DAO – for database operations using DAO pattern

● Spring JDBC – for JDBC and DataSource support.

● Spring ORM – for ORM tools support such as Hibernate

● Spring Web Module – for creating web applications.

● Spring MVC – Model-View-Controller implementation for creating web applications, web

services etc.
Q3. List some of the important annotations in annotation-based
Spring configuration.

The important annotations are:

● @Required

● @Autowired

● @Qualifier

● @Resource

● @PostConstruct

● @PreDestroy
Q4. Explain Bean in Spring and List the different Scopes of
Spring bean.

Beans are objects that form the backbone of a Spring application. They are managed by the

Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and

managed by a Spring IoC container.

● Singleton: Only one instance of the bean will be created for each container.

This is the default scope for the spring beans. While using this scope,

make sure spring bean doesn’t have shared instance variables otherwise it

might lead to data inconsistency issues because it’s not thread-safe.

● Prototype: A new instance will be created every time the bean is requested.

● Request: This is same as prototype scope, however it’s meant to be used

for web applications. A new instance of the bean will be created for each

HTTP request.

● Session: A new bean will be created for each HTTP session by the

container.

● Global-session: This is used to create global session beans for Portlet

applications.

Q5. Explain the role of DispatcherServlet and


ContextLoaderListener.
DispatcherServlet is basically the front controller in the Spring MVC application

as it loads the spring bean configuration file and initializes all the beans that have

been configured. If annotations are enabled, it also scans the packages to


configure any bean annotated with @Component, @Controller, @Repository or

@Service annotations.

ContextLoaderListener, on the other hand, is the listener to start up and shut


down the WebApplicationContext in Spring root. Some of its important functions
includes tying up the lifecycle of Application Context to the lifecycle of the
ServletContext and automating the creation of ApplicationContext.

Q7. What is autowiring in Spring? What are the autowiring


modes?
Autowiring enables the programmer to inject the bean automatically. We don’t

need to write explicit injection logic. Let’s see the code to inject bean using

dependency injection.

1. <bean id=“emp” class=“com.javatpoint.Employee” autowire=“byName” />

The autowiring modes are given below:

No. Mode Description

1) no this is the default mode, it means autowiring is not enabled.

2) byName Injects the bean based on the property name. It uses setter
method.
3) byType Injects the bean based on the property type. It uses setter
method.
4) It injects the bean using constructor
constructor

Q9. What are some of the important Spring annotations which


you have used?
Some of the Spring annotations that I have used in my project are:

@Controller – for controller classes in Spring MVC project.

@RequestMapping – for configuring URI mapping in controller handler methods.

This is a very important annotation, so you should go through Spring MVC

RequestMapping Annotation Examples

@ResponseBody – for sending Object as response, usually for sending XML or

JSON data as response.

@PathVariable – for mapping dynamic values from the URI to handler method

arguments.

@Autowired – for autowiring dependencies in spring beans.

@Qualifier – with @Autowired annotation to avoid confusion when multiple

instances of bean type is present.

@Service – for service classes.

@Scope – for configuring scope of the spring bean.

@Configuration, @ComponentScan and @Bean – for java based configurations.

AspectJ annotations for configuring aspects and advices, @Aspect, @Before,

@After, @Around, @Pointcut etc.

Q10. How to integrate Spring and Hibernate Frameworks?


We can use Spring ORM module to integrate Spring and Hibernate frameworks, if

you are using Hibernate 3+ where SessionFactory provides current session, then
you should avoid using HibernateTemplate or HibernateDaoSupport classes and

better to use DAO pattern with dependency injection for the integration.

SPRING VS SPRING BOOT

Q : Spring Boot vs Spring MVC vs Spring - How do they compare?

Spring Framework

Most  important  feature of Spring Framework is Dependency Injection. At the core of all 


Spring Modules is Dependency Injection or IOC Inversion of Control. 

When  DI  or  IOC  is  used  properly,  we  can  develop  loosely 
coupled  applications.  And  loosely  coupled  applications  can  be 
easily unit tested. 

Spring MVC

Spring  MVC  Framework  provides  decoupled  way  of  developing  web applications. With 


simple  concepts  like  Dispatcher  Servlet,  ModelAndView  and  View  Resolver,  it  makes  it 
easy to develop web applications. 

Spring Boot

The  problem  with  Spring  and  Spring  MVC  is  the  amount  of 
configuration that is needed. 

<bean

class="org.springframework.web.servlet.view.Internal
ResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<mvc:resources mapping="/webjars/**"
location="/webjars/"/>

Spring  Boot  solves  this  problem  through  a  combination  of 


Auto  Configuration  and  Starter  Projects.  Spring  Boot  also 
provide  a  few  non  functional  features  to  make  building 
production ready applications faster. 

Q : What is Auto Configuration?

Spring  Boot  looks at a) Frameworks available on the 


CLASSPATH  b)  Existing  configuration  for  the 
application.  Based  on  these,  Spring  Boot  provides 
basic  configuration  needed  to  configure  the 
application  with  these  frameworks.  This  is  called 
Auto Configuration. 

Q : What are Spring Boot Starter Projects?


Starters  are  a  set  of  convenient  dependency 
descriptors  that  you  can  include  in  your  application. 
You  get  a  one-stop-shop  for  all  the  Spring  and 
related  technology  that  you  need,  without  having  to 
hunt  through  sample  code  and  copy  paste  loads  of 
dependency descriptors. 

For  example,  if  you  want  to  get  started  using  Spring  and  JPA  for 
database  access,  just  include  the  spring-boot-starter-data-jpa 
dependency in your project, and you are good to go. 

Q : What are the other Starter Project Options that Spring Boot provides?

● pring-boot-starter-web-services - SOAP Web Services 


● spring-boot-starter-web - Web & RESTful applications 
● spring-boot-starter-test  -  Unit  testing  and  Integration 
Testing 
● spring-boot-starter-jdbc - Traditional JDBC 
● spring-boot-starter-hateoas  -  Add  HATEOAS  features  to 
your services 
● spring-boot-starter-security  -  Authentication  and 
Authorization using Spring Security 
● spring-boot-starter-data-jpa  -  Spring  Data  JPA  with 
Hibernate 
● spring-boot-starter-data-rest  -  Expose  Simple  REST 
Services using Spring Data REST 

Q : How can I add custom JS code with Spring Boot?

Create  a  folder  called  static  under  resources  folder.  You  can  put 
your static content in that folder. 

For  your  example  the  path  to  myapp.js  would  be 


resources\static\js\myapp.js 

You can refer to it in jsp using 

<script src="/js/myapp.js"></script>

Q : What is Spring Data REST?

Spring  Data  REST  can  be  used  to  expose  HATEOAS  RESTful 
resources around Spring Data repositories. 

An example using JPA is shown below 

@RepositoryRestResource​(c ​ ollectionResourceRel ​=
"todos",​ ​ path ​=​ ​"todos"​)
public​ ​interface​ T​ odoRepository
e
​ xtends PagingAndSortingRepository< ​ ​Todo​,
Long>​ ​ ​{
Without  writing  a  lot  of  code,  we  can  expose  RESTful  API  around 
Spring Data Repositories. 

A few example REST Services are shown below: 

POST
● URL : http://localhost:8080/todos 
● Use Header : Content-Type:application/json 
● Request Content 

{
"user": "Jill",
"desc": "Learn Hibernate",
"done": false
}

Response Content 

{
"user": "Jill",
"desc": "Learn Hibernate",
"done": false,
"_links": {
"self": {
"href": "http://localhost:8080/todos/1"
},
"todo": {
"href": "http://localhost:8080/todos/1"
}
}
}

The response contains the href of the newly created resource. 

Q : How does path=”users”, collectionResourceRel=”users” work with


Spring Data Rest?

@RepositoryRestResource(collectionResourceRel =
"users", path = "users")

public interface UserRestRepository extends


PagingAndSortingRepository<User, Long>

● path  -  The  path  segment  under  which  this  resource  is  to  be 
exported. 
● collectionResourceRel  - The rel value to use when generating 
links  to  the  collection  resource.  This  is  used  when  generating 
HATEOAS links. 

Q : What is the difference between RequestMapping and GetMapping?

● RequestMapping  is  generic  -  you  can  use  with  GET,  POST, 


PUT  or  any  of  the  other  request  methods  using  the  method 
attribute on the annotation. 
● GetMapping  is  specific  to  GET  request  method.  It’s  just  an 
extension of RequestMapping to improve clarity. 
 

HIBERNATE

What is Hibernate Framework?


Object-relational mapping or ORM is the programming technique to map
application domain model objects to the relational database tables. Hibernate is
java based ORM tool that provides framework for mapping application domain
objects to the relational database tables and vice versa.

What is Java Persistence API (JPA)?


Java Persistence API (JPA) provides specification for managing the relational
data in applications. Current JPA version 2.1 was started in July 2011 as JSR 338.
JPA 2.1 was approved as final on 22 May 2013.

Name some important interfaces of Hibernate


framework?

Some of the important interfaces of Hibernate framework are:

1. SessionFactory (org.hibernate.SessionFactory): SessionFactory is an


immutable thread-safe cache of compiled mappings for a single
database. We need to initialize SessionFactory once and then we can
cache and reuse it. SessionFactory instance is used to get the
Session objects for database operations.
2. Session (org.hibernate.Session): Session is a single-threaded,
short-lived object representing a conversation between the
application and the persistent store. It wraps JDBC
java.sql.Connection and works as a factory for
org.hibernate.Transaction​​. We should open session only when
it’s required and close it as soon as we are done using it. Session
object is the interface between java application code and hibernate
framework and provide methods for CRUD operations.
3. Transaction (org.hibernate.Transaction): Transaction is a
single-threaded, short-lived object used by the application to specify
atomic units of work. It abstracts the application from the underlying
JDBC or JTA transaction. A org.hibernate.Session might span
multiple org.hibernate.Transaction in some cases.

What is hibernate configuration file?


Hibernate configuration file contains database specific configurations and used
to initialize SessionFactory. We provide database credentials or JNDI resource
information in the hibernate configuration xml file. Some other important parts of
hibernate configuration file is Dialect information, so that hibernate knows the
database type and mapping file or class details.

What is hibernate mapping file?


Hibernate mapping file is used to define the entity bean fields and database table
column mappings. We know that JPA annotations can be used for mapping but
sometimes XML mapping file comes handy when we are using third party classes
and we can’t use annotations.

Name some important annotations used for Hibernate


mapping?
Hibernate supports JPA annotations and it has some other annotations in
org.hibernate.annotations package. Some of the important JPA and
hibernate annotations used are:

1. javax.persistence.Entity: Used with model classes to specify that they


are entity beans.
2. javax.persistence.Table: Used with entity beans to define the
corresponding table name in database.
3. javax.persistence.Access: Used to define the access type, either field
or property. Default value is field and if you want hibernate to use
getter/setter methods then you need to set it to property.
4. javax.persistence.Id: Used to define the primary key in the entity bean.
5. javax.persistence.EmbeddedId: Used to define composite primary key
in the entity bean.
6. javax.persistence.Column: Used to define the column name in
database table.
7. javax.persistence.GeneratedValue: Used to define the strategy to be
used for generation of primary key. Used in conjunction with
javax.persistence.GenerationType​​ enum.
8. javax.persistence.OneToOne: Used to define the one-to-one mapping
between two entity beans. We have other similar annotations as
OneToMany​​, ​ManyToOne​​ and ​ManyToMany
9. org.hibernate.annotations.Cascade: Used to define the cascading
between two entity beans, used with mappings. It works in
conjunction with ​org.hibernate.annotations.CascadeType
10. javax.persistence.PrimaryKeyJoinColumn: Used to define the
property for foreign key. Used with
org.hibernate.annotations.GenericGenerator and
org.hibernate.annotations.Parameter

Hibernate SessionFactory is thread safe?


Internal state of SessionFactory is immutable, so it’s thread safe. Multiple threads
can access it simultaneously to get Session instances.

Hibernate Session is thread safe?


Hibernate Session object is not thread safe, every thread should get it’s own
session instance and close it after it’s work is finished.

What is hibernate caching? Explain Hibernate first


level cache?
As the name suggests, hibernate caches query data to make our application
faster. Hibernate Cache can be very useful in gaining fast application
performance if used correctly. The idea behind cache is to reduce the number of
database queries, hence reducing the throughput time of the application.

Hibernate first level cache is associated with the Session object. Hibernate first
level cache is enabled by default and there is no way to disable it. However
hibernate provides methods through which we can delete selected objects from
the cache or clear the cache completely.

Any object cached in a session will not be visible to other sessions and when the
session is closed, all the cached objects will also be lost.
How to configure Hibernate Second Level Cache
using EHCache?
EHCache is the best choice for utilizing hibernate second level cache. Following
steps are required to enable EHCache in hibernate application.

● Add hibernate-ehcache dependency in your maven project, if it’s not


maven then add corresponding jars
● Add below properties in hibernate configuration file.
○ Create EHCache configuration file, a sample file myehcache.xm
● Annotate entity beans with @Cache annotation

What are different states of an entity bean?


An entity bean instance can exist is one of the three states.

1. Transient: When an object is never persisted or associated with any


session, it’s in transient state. Transient instances may be made
persistent by calling save(), persist() or saveOrUpdate(). Persistent
instances may be made transient by calling delete().
2. Persistent: When an object is associated with a unique session, it’s in
persistent state. Any instance returned by a get() or load() method is
persistent.
3. Detached: When an object is previously persistent but not associated
with any session, it’s in detached state. Detached instances may be
made persistent by calling update(), saveOrUpdate(), lock() or
replicate(). The state of a transient or detached instance may also be
made persistent as a new persistent instance by calling merge().
What is difference between sorted collection and
ordered collection, which one is better?

Ordered list is better than sorted list because the actual sorting is done at
database level, that is fast and doesn’t cause memory issues.

What is the benefit of Hibernate Criteria API?


Hibernate provides Criteria API that is more object oriented for querying the
database and getting results. We can’t use Criteria to run update or delete queries
or any DDL statements. It’s only used to fetch the results from the database using
more object oriented approach.

Some of the common usage of Criteria API are:

● Criteria API provides Projection that we can use for aggregate


functions such as sum(), min(), max() etc.
● Criteria API can be used with ProjectionList to fetch selected columns
only.
● Criteria API can be used for join queries by joining multiple tables,
useful methods are createAlias(), setFetchMode() and setProjection()
● Criteria API can be used for fetching results with conditions, useful
methods are add() where we can add Restrictions.
● Criteria API provides addOrder() method that we can use for ordering
the results.

What is Hibernate Proxy and how it helps in lazy


loading?
Hibernate uses proxy object to support lazy loading. Basically when you load
data from tables, hibernate doesn’t load all the mapped objects. As soon as you
reference a child or lookup object via getter methods, if the linked entity is not in
the session cache, then the proxy code will go to the database and load the
linked object. It uses javassist to effectively and dynamically generate
sub-classed implementations of your entity objects.

Which design patterns are used in Hibernate


framework?
Some of the ​design patterns​​ used in Hibernate Framework are:

● Domain Model Pattern – An object model of the domain that


incorporates both behavior and data.
● Data Mapper – A layer of Mappers that moves data between objects
and a database while keeping them independent of each other and the
mapper itself.
● Proxy Pattern​​ for lazy loading
● Factory pattern​​ in SessionFactory

What is Hibernate Proxy and how it helps in lazy


loading?
Hibernate uses proxy object to support lazy loading. Basically when you load
data from tables, hibernate doesn’t load all the mapped objects. As soon as you
reference a child or lookup object via getter methods, if the linked entity is not in
the session cache, then the proxy code will go to the database and load the
linked object. It uses javassist to effectively and dynamically generate
sub-classed implementations of your entity objects.

How to integrate Hibernate and Spring frameworks?


1. Add hibernate-entitymanager, hibernate-core and spring-orm
dependencies.
2. Create Model classes and corresponding DAO implementations for
database operations. Note that DAO classes will use SessionFactory
that will be injected by Spring Bean configuration.
3. If you are using Hibernate 3, you need to configure
org.springframework.orm.hibernate3.LocalSessionFactory
Bean or
org.springframework.orm.hibernate3.annotation.Annotatio
nSessionFactoryBean in Spring Bean configuration file. For
Hibernate 4, there is single class
org.springframework.orm.hibernate4.LocalSessionFactory
Bean​​ that should be configured.
4. Note that we don’t need to use Hibernate Transaction Management,
we can leave it to Spring declarative transaction management using
@Transactional​​ annotation.

LINUX

Linux operating system is consist of 3 components which are as below:


● Kernel: ​Linux is a monolithic kernel that is free and open source software that is
responsible for managing hardware resources for the users.
● System Library: ​System Library plays a vital role because application
programs access Kernels feature using system library.
● System Utility: ​System Utility performs specific and individual level tasks.

3. Describe BASH.

Answer: BASH stands for Bourne Again Shell. BASH is the UNIX shell for the GNU
operating system. So, BASH is the command language interpreter that helps you to enter
your input, and thus you can retrieve information

5. What do you understand by CLI?

CLI is an acronym for Command Line Interface. We have to provide the information to the
computer so that it can perform the function accordingly.

9. Where is password file located in Linux and how can


you improve the security of password file?

in Linux is stored in/etc/passwd that is a compatible format. But this file is used to get the
user information by several tools. Here, security is at risk. So, we have to make it secured.

To improve the security of the password file, instead of using a compatible format we can
use shadow password format. So, in shadow password format, the password will be stored
as single “x” character which is not the same file (/etc/passwd). This information is stored in
another file instead with a file name /etc/shadow.

Explain system calls used for process management?


Fork(): It is used to create a new process

Exec(): It is used to execute a new process

Wait(): It is used to make the process to wait

Exit(): It is used to exit or terminate the process

Getpid(): It is used to find the unique process ID

Getppid(): It is used to check the parent process ID

Nice(): It is used to bias the currently running process property

Edit File without oppening: ​>cat file.txt

sed 's/sed/vi/' file.txt

Explain grep command and its use

grep command in Linux is used to search a specific pattern. Grep command will
help you to explore the string in a file or multiple files.

Command content type

head: to check the starting of a file.

tail: to check the ending of the file. It is the reverse of head command.

cat: used to view, create, concatenate the files.

rrep: used to find the specific pattern or string in a file.


more: used to display the text in the terminal window in pager form.

less: used to view the text in the backward direction and also provides
single line movement.

ANGULAR

AngularJS Interview Question #1

What are the basic steps to unit test an AngularJS filter?

(Question provided by ​Daniel Lamb)​

1. Inject the module that contains the filter.

2. Provide any mocks that the filter relies on.

3. Get an instance of the filter using ​$filter('yourFilterName')​.

4. Assert your expectations.

What should be the maximum number of concurrent “watches”? Bonus: How

would you keep an eye on that number?

(Question provided by ​Daniel Lamb)​


TL;DR Summary: To reduce memory consumption and improve performance

it is a good idea to limit the number of watches on a page to 2,000. A utility

called ​ng-stats​ can help track your watch count and digest cycles.

ngularJS Interview Question #3

How do you share data between controllers?

(Question provided by ​Tome Pejoski)​

Create an AngularJS service that will hold the data and inject it inside of the

controllers.

Using a service is the cleanest, fastest and easiest way to test. However,

there are couple of other ways to implement data sharing between controllers,

like:

– Using ​events

– Using ​$parent​, ​nextSibling​, ​controllerAs​, etc. to directly access the controllers


– Using the ​$rootScope​ to add the data on (not a good practice)

The methods above are all correct, but are not the most efficient and easy to

test.

AngularJS Interview Question #6

Where should we implement the DOM manipulation in AngularJS?

(Question provided by ​Tome Pejoski)​

In the directives. DOM Manipulations should not exist in controllers, services

or anywhere else but in directives.

● What are different ways to create objects? 


● You can create Object by 
○ object literals 
○ Object.create 
○ constructors 
● 0
● Q2. 
● What is the default value of a constructor’s 
prototype? 
● A plain, empty object that derives from Object.prototype is the 
default value of a constructor’s prototype 
● 0
● Q3. 
● List some benefits of JSON over XML? 
○ It is faster and lighter than XML as on the wire data format 
○ XML data is typeless while JSON objects are typed 
○ JSON types: Number, Array, Boolean, String 
○ XML data are all string 
○ Data is readily available as JSON object is in your JavaScript 
○ Fetching values is as simple as reading from an object 
property in your JavaScript code 
● 0
● Q4. 
● What is the difference between JSON and JSONP? 
○ JSON: JSON is a simple data format used for communication 
medium between different systems 
○ JSONP: It is a methodology for using that format with 
cross-domain ajax requests while not being affected by same 
origin policy issue. 
● 0
● Q5. 
● Who is the Father of JSON and What is the 
scripting language JSON is based on? 
● Douglas Crockford called as the Father of JSON. JSON is based on 
ECMAScript​. 
● 0
● Q6. 
● What is JSON-RPC? List some Features of 
JSON-RPC-Java 
● JSON-RPC: JSON-RPC is a simple remote procedure call protocol 
similar to XML-RPC although it uses the lightweight JSON format 
instead of XML. 
● JSON-RPC-Java is a ​Java i​ mplementation of the JSON-RPC 
protocol.Below is list of some of its features 
○ Dynamically call server-side Java methods from JavaScript 
DHTML web applications. No Page reloading. 
○ Asynchronous communications. 
○ Transparently maps Java objects to J ​ avaScript ​objects. 
○ Lightweight protocol similar to XML-RPC although much 
faster. 
○ Leverages J2EE security model with session specific exporting 
of objects. 
○ Supports Internet Explorer, Mozilla, Firefox, Safari, Opera, and 
Konqueror. 
● 0
● Q7. 
● What are natively supported JSON types? 
● Following data types are natively supported in JSON. 
○ Numbers: Integer, float or Double 
○ String: string of Unicode characters, must be rapped into 
double quotes “” 
○ Boolean: True or false 
○ Array: ordered list of 0 or more values 
○ Objects : An unordered collection key/ value pairs 
○ Null: An Empty value 
● Read Latest J
​ query interview questions 

● 0
● Q8. 
● What is BSON? 
● BSON is the superset of JSON, which used by M ​ ongoDB​.BSON 
supports the embedding of documents and arrays within other 
documents and arrays. BSON also contains extensions that allow 
representation of data types that are not part of the JSON spec. 
● 0
● Q9. 
● How to convert an Object into JSON? What is the 
full syntax of JSON.stringify? 
● JSON.stringify method is used to convert an Javascript Object into 
JSON. 
● Syntax: 
● let json = JSON.stringify(value[, replacer, space])
● 0
● Q10. 
● What JS-specific properties are skipped by 
JSON.stringify method? 
● Following JS-specific properties are skipped by JSON.stringify 
method 
○ Function properties (methods). 
○ Symbolic properties. 
○ Properties that store undefined. 
● 0
● Q11. 
● What is JSON? For what is used for? 
● JSON (JavaScript Object Notation) is a data storage and 
communication format based on key-value pair of JavaScript object 
literals. It is a lightweight text-based open standard designed for 
human-readable data interchange which is derived from the 
JavaScript programming language for representing simple data 
structures and associative arrays, called objects. 
● In JSON 
○ all property names are surrounded by double quotes. 
○ values are restricted to simple data: no function calls, 
variables, comments, or computations. 
● JSON is used for communication between javascript and serverside 
technologies. 

● 0
● Q12. 
● How to convert Javascript objects into JSON? 
● JSON.stringify(value); is used to convert Javascript objects into JSON. 
● Example Usage: 
● var obj={"website":"Onlineinterviewquestions"};
JSON.stringify(obj); //
'{"website":"Onlineinterviewquestions"}'

● 0
● Q13. 
● List types Natively supported by JSON? 
● JSON supports Objects, Arrays, Primitives (strings, numbers, boolean 
values (true/false), null) data types. 
● 0
● Q14. 
● What does Object.create do? 
● Object.create creates a new object with the specified prototype 
object and properties. 
● 0
● Q15. 
● What does hasOwnProperty method do? 
● It returns true if the property was set on an actual object rather than 
inherited. 
● 0
● Q16. 
● What does $.parseJSON() do ? 
● $.parseJSON() takes a well-formed JSON string and returns the 
resulting JavaScript value. 
● 0
● Q17. 
● How do you decode a JSON string? 
● Use JSON.parse method to decode a JSON string into a Javascript 
object. 
● 0
● Q18. 
● How to delete an index from JSON Obj? 
● Deleting an Element from JSON Obj 
● var exjson = {'key':'value'};
delete exjson['key'];

You might also like