JAVA Interview Question NEW 2
JAVA Interview Question NEW 2
JAVA Interview Question NEW 2
1. Explain System.out.println(); ?
Ans- In Java, System.out.println() is a statement which prints the argument passed to it. The println() method display
results on the monitor.
Q. Garbage collection: -> Garbage collection on regular basic it keeps removing unused object from RAM and
thus avoid overflow of memory. This is how memory management is done in efficient manner in java.
Stack:-> It maintain your program execution flow. And it’s follow LIFO.
Heap:-> Object are created in heap memory.
Static Variables is like a global Non-Static variable is a like local It can’t be accessed outside that
variable and is available to all variable and they can be accessed method.
method. through only instance of a class.
4. Explain about Constructors ? Ans- Constructors should have same name as that of class.
Whenever an object is created constructor is being called.
Constructors are permanently void and hence they cannot return any value.
Because it is void we can only use keywords in it.
Supplying values to constructor, then yes we can create multiple constructors. In constructor, method name
and class name can be same.
Constructor chaining: When we call a constructor from another constructor using This keyword then it is called
as Constructor Chaining.
Default Constructor: A constructor is called "Default Constructor" when it doesn't have any parameter. The
default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
7. What is super keyword ? Ans- Using Super Keyword, we can access the member of parent class.
Using super keyword, we can access static and non static member both.
• Super keyword can not be used inside static context.
• We can use super keyword only when inheritance is happening otherwise we cannot use super keyword.
14. Explain new features of Java 8 ?( default , functional interfaces , lambda expressions ,
stream API ) ? Ans- Default Keyword: Default keyword was introduced in version 8 of java using which we can
develop complete method in an interface.
Functional Interface: It should consist of only one incomplete method in it.
In a functional Interface we can have any number of default methods but incomplete method should be only one.
Lamdas Expression: The advantage of lamdas expression is we can reduce number of times of code.
Stream API: - Stream helps as to manipulate collection data and this was introduced in version 8 on java.
Optional class: - optional class make handling NullPointerException much easier, without optional class to handle
NullPointerException we use multiple try catch block which make your code retender. This feature is introduced
in version 1.8 in java.
16.Explain about Exceptions ? Ans- Whenever a bad input is given then it stops the
program updroply and that is called exceptions.
-To handle exception in java we use try and catch block.
When any line of code in try block causes exception then try block create exception
object and that exception object address is given
To catch block . Catch block will now suppress the exception and once the exception is suppressed, the further code
will continue to execution.
-To get exact line number where exception occurs we use printStackTrace.
Types of exception:
i)Run time exception (Unchecked Exception ): If we get exception while running .class file then it is called as run time
exception. e.g. -Arithmetic Exception
-NullPointer Exception
-Numberformat Exception
-ArrayIndexOutOf Bound Exception
-classCasting Exception ii)Compile time exception (checked exception): If an exception occurs when .java file is
converted to .class file then it is called as compile time exception .e.g.
-SQL Exception
-IO Exception
-FileNot Found Exception
-ClassNotFound Exception 17. Explain about multi catch ? Ans- A try block can be followed by one or more
catch blocks. Each catch block must contain a different exception handler. So, if we have to perform different tasks at
the occurrence of different exceptions, we use java multi-catch block.
StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
number of elements exceeds from its capacity. the total number of elements exceeds than its capacity.
task.
In a runnable interface, one needs to override the run() In order to use Callable, you need to override the call()
method in Java.
34.Explain Thread priority ? Ans- Thread Priority decide which thread is going to run first and which thread will run
later.
If we set the priority then it is a request made to the thread scheduler where there is no assurity that it will be
approve and process.
The minimum thread priority is 1, maximum thread priority is 10 and the normal thread priority is 5. However we can
set the thread priority with a number anything between 1 to 10.
35.Explain thread scheduler?(wait , notify , notify all , sleep ) Ans- wait(): It tells the calling thread to give
up the lock and go to sleep until some other thread enters the same monitor and calls notify(). notify(): It wakes up one
single thread called wait() on the same object. It should be noted that calling notify() does not give up a lock on a
resource. notifyAll(): It wakes up all the threads called wait() on the same object.
39.Difference between throws and throw keyword ? Ans- Throws Keyword: Throws keyword is applied on a
method if any exception occurs in the method then the exception will be passed on to the calling statement of the
method.
Throw Keyword: Throw keyword helps us to create customized exception as per the requirement of the developer.
41.What is tokenizer ?
Ans- The Tokenizer class allows us to break a String into tokens. It is simple way to break a String. It is a legacy class
of Java.
42.What is cloning ? Ans- The process of creating the replica of a particular object by copying the content of one
object completely into another object is known as Cloning.
43.What is hash code ?
Ans- Hash Code is a method present inside object class in java 44.
What is JDBC ?
Ans- JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.
45.What is main principle of SQL ? Ans- SQL is used to communicate with a database. According to ANSI
(American National Standards Institute), it is the standard language for relational database management systems.
SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database.
46.Explain about Collections?
Ans- Collection stores group of object in it. In Java collection is a framework which has readily available logic to deal
with different data structure.
The ArrayList class implements the LinkedList implements the Vector uses a dynamic array to store
List interface. It uses a dynamic array Collection interface. It uses a doubly the data elements. It is similar to
to store the duplicate element of linked list internally to store the ArrayList. However, It is synchronized
different data types. The ArrayList elements. It can store the duplicate and contains many methods that are
class maintains the insertion order elements. It maintains the insertion not the part of Collection framework.
and is nonsynchronized. order and is not synchronized. In
LinkedList, the manipulation is fast
because no shifting is required.
HashSet TreeSet
HashSet uses hashtable internally. It uses hashing to TreeSet contains unique elements only. It sorts the data
inject the data into the data base. It will contain only in ascending order.
unique elements. It does not maintain insertion order.
This class permit the null elements.
HashMap is Faster.
56.Difference between hash set , hash map , hash table ? Ans-
Hash HashMap HashTable
Set
HashSet uses hashtable internally. It HashMap internally uses hashtable. HashTable is an associated array
uses hashing to inject the data into To inject data into hashtable, it uses where in the value store as a key
the data base. It will contain only hashing technique. A hashmap stores value pair.
unique elements. It does not the data as key value pair. Hasmap is Initial size of a hashtable is 16 byte
maintain insertion order. This class not synchronized. when load ratio becomes 75% that is
out of 16 twelve elements are
permit the null elements.
injected into the table then the size
of table becomes double
automatically.
HashTable is Synchronized.
1.Comparable provides a single sorting sequence. In The Comparator provides multiple sorting sequences. In
other words, we can sort the collection on the basis of a other words, we can sort the collection on the basis of
single element such as id, name, and price. multiple elements such as id, name, and price etc.
2.Comparable affects the original class. Comparator doesn't affect the original class.
3.Comparable provides compareTo() methodto sort Comparator provides compare() method to sort
elements. elements.
Comparator Interface:- Comparator is actually interface is used to order the object of user defined classes.
Comparator is an interface that compares to object if in sorting object 1 comes first then object 2 then it will
return negative value but if while sorting object 2 comes first and then object 1 it will return positive value, If both
object are same it will return zero.
59.What is dynamic binding and static binding ? Ans- Static Binding: When type of the object is
determined at compiled time, it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic Binding: When type of the object is determined at run-time, it is known as dynamic binding.
61.J unit
Ans- JUnit is an open-source testing framework for java programmers. The java programmer can create test cases
and test his/her own code. To perform unit testing, we need to create test cases. The unit test case is a code which
ensures that the program logic works as expected.
62.SOAP vs REST
Ans-
SOAP REST
63.What is SDLC ? Ans- SDLC is a systematic process for building software that ensures the quality and
correctness of the software built. SDLC process aims to produce high-quality software that meets customer
expectations. The system development should be complete in the pre-defined time frame and cost. SDLC consists
of a detailed plan which explains how to plan, build, and maintain specific software. Every phase of the SDLC life
Cycle has its own process and deliverables that feed into the next phase. SDLC stands for Software Development
Life Cycle and is also referred to as the Application Development life-cycle.
64.Drop vs truncate Ans- Drop: It is a Data Definition Language Command (DDL). It is used to drop the whole
table. With the help of the “DROP” command we can drop (delete) the whole structure in one go i.e. it removes
the named elements of the schema. By using this command the existence of the whole table is finished or say lost.
Truncate: It is also a Data Definition Language Command (DDL). It is used to delete all the rows of a relation (table)
in one go. With the help of the “TRUNCATE” command, we can’t delete the single row as here WHERE clause is not
used. By using this command the existence of all the rows of the table is lost. It is comparatively faster than the
delete command as it deletes all the rows fastly.
65.@component
Ans-@Component is a class-level annotation. It is used to denote a class as a Component. We can use @Component
across the application to mark the beans as Spring’s managed components. A component is responsible for some
operations.
66.What is server validation and Clint validation Ans- Clint Side validation: Customer Side approval
is done on the program on which client is entering information in the frame which are started from server side.
These are basically done through JavaScript for the information which is entered.
Server Side validation: Server-Side Validation is done on server where application is put away and got to. This
approval is done to shield application from the client who sidesteps the approval from the customer side and attempt
to hurt inner application.
67.What is SAM interface ? Ans- An interface having only one abstract method is known as a functional
interface and also named as Single Abstract Method Interfaces (SAM Interfaces). One abstract method means that
either a default method or an abstract method whose implementation is available by default is allowed.
68.Difference between var and let in JavaScript ?
Ans- Var and let are both used for variable declaration in javascript but the difference between them is that var is
function scoped and let is block scoped. It can be said that a variable declared with var is defined throughout the
program as compared to let.
69.Agile methodology ? Ans- Agile Methodology meaning a practice that promotes continuous iteration of
development and testing throughout the software development lifecycle of the project. In the Agile model in
software testing, both development and testing activities are concurrent, unlike the Waterfall model.
70.Hibernate architecture
The Hibernate architecture includes many objects such as persistent object, session factory, transaction factory,
connection factory, session, transaction etc.
The Hibernate architecture is categorized in four layers.
I. Java application layer
II. Hibernate framework layer
III. Backhand api layer
IV. Database layer
71.Spring initialize
Ans- Spring Initializr is a web-based tool provided by the Pivotal Web Service. With the help of Spring Initializr, we
can easily generate the structure of the Spring Boot Project. It offers extensible API for creating JVM-based projects.
72.Spring security
Ans- Spring Security is a framework that focuses on providing both authentication and authorization to Java
applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to
meet custom requirements.
73.Difference between session and session factory ? Ans- Session:- The session object provides an
interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC
connection. Session interface provides methods to insert, update and delete the object. It also provides factory methods
for Transaction, Query and Criteria.
Session Factory:-The Session Factory is a factory of session and client of Connection Provider. It holds second
level cache (optional) of data. Session Factory interface provides factory method to get the object of Session.
74.Replace and replace all methods ? Ans- The replace() method is one of the most used string methods for
replacing all the occurrences of a character with the given character. The replace() method of JDK 1.5 replaces the char
and a sequence of char values. The replaceAll() method is similar to the String.replaceFirst() method. The only
difference between them is that it replaces the sub-string with the given string for all the occurrences present in the
string.
75.What is DDL , DML Ans- DDL: DDL stands for Data Definition Language. As the name suggests, the DDL
commands help to define the structure of the databases or schema. When we execute DDL statements, it takes effect
immediately. The changes made in the database using this command are saved permanently because its commands are
auto-committed. DML: It stands for Data Manipulation Language. The DML commands deal with the manipulation of
existing records of a database. It is responsible for all changes that occur in the database. The changes made in the
database using this command can't save permanently because its commands are not autocommitted.
For the first time, when we start Tomcat init() method will run and it will run only once. Then
services method (doGet,doPost) are called and it can run any number of times. Finally, when
tomcat runs destroy method is called, the servlet life cycle comes to end. JSP Life Cycle:
JSP translator will translate JSP file into servlet. This servlet will
consist of three important methods:
i)-jsp int () – This method will run only once after tomcat started.
ii)-jsp Services () – This method can be called any number of times depending on business requirement. iii)jsp
destroy method() – This is called by tomcat and this is last method to run. When this method runs then it
means jsp life cycle come to an end.
2. What is servlet , jsp , html pages ? Ans- Servlet: Servlet is a Java class that extends httpservlet and is
responsible to perform backend coding. JSP: Java Servlet Page- JSP helps us to embed partial java code inside html.
3. What is Inter Servlet connectivity ? ( ISC ) Ans- When one servlet calls another servlet using request
dispatcher concept then it is called as Inter Servlet Communication (ISC).
4. What are session variables ?
Ans- Once we store the data in session variable then that we can access across the application.
5. Explain about JSP tags ?
Ans- JSP Tags are-
i) Scrip let Tag
<% Java code………%>
ii) Declaration Tag <%! Java
code….%> iii)Expression Tag
<%= java code…….%> iv)Directive Tag
6. Explain about MVC architecture? Ans- MVC (Model View Controller) Architecture:
MVC architecture is a three-layered architecture wherein all HTML code, JSP code is kept in view layer. Controller
layer is responsible to interact with a View, take the data from view and gives it to model layer. Business logical
implementation/ database implementation is done in model layer, the output of the model layer is given to controller
and that data further controller gives it to view.
This architecture helps us to maintain the application in easy manner.
MVC architecture flow: -View ->Controller ->model->Controller->view.
Ans- Spring: Spring Framework is the most popular application development framework of Java. The main feature of the
Spring Framework is dependency Injection or Inversion of Control (IoC). With the help of Spring Framework, we can develop a
loosely coupled application. It is better to use if application type or characteristics are purely defined. Spring Boot: Spring Boot
is a module of Spring Framework. It allows us to build a stand-alone application with minimal or zero configurations. It is better
to use if we want to develop a simple Spring-based application or RESTful services.
18.Explain about spring bean?
Ans- The objects that form the backbone of your application and that are managed by the Spring IoC container are called
beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
These beans are created with the configuration metadata that you supply to the container.
19.Explain about web services ?
Ans- Web service is a technology to communicate one programming language with another. For example, java programming
language can interact with PHP and .Net by using web services. In other words, web service provides a way to achieve
interoperability.
21.Explain about Session tracking system ? Ans- Session Tracking is a way to maintain state (data) of an user. It
is also known as session management in servlet. It is used to recognize the particular user.
23.What is API? Ans- API stands for application program interface. A programmer writing an application program can
make a request to the Operating System using API. It is a set of routines, protocols and tools for building software and
applications. It may be any type of system like a web-based system, operating-system or a database System.
Q.Explain new features of Java 8 ?( default , functional interfaces , lambda expressions , stream API ) ?
Ans- Default Keyword: - Default keyword was introduced in version 8 of java using which we can develop complete
method in an interface.
Functional Interface: - It should consist of only one incomplete method in it.
In a functional Interface we can have any number of default methods but incomplete method should be only one.
Lamdas Expression: - The advantage of lamdas expression is we can reduce number of times of code.
Stream API: - Stream helps as to manipulate collection data and this was introduced in version 8 on java.
Optional class: - optional class make handling NullPointerException much easier, without optional class to handle
NullPointerException we use multiple try catch block which make your code retender. This feature is introduced
in version 1.8 in java.
Web –Services:
Web Services help us to integrate heterogeneous and homogeneous application.
There are two ways we can implement web services.
SOAP (Simple Object Access Protocol)- Here we exchange the data between application using xml file.
Implementation of SOAP is difficult because it is complex to parse xml file.
REST (Representational State Transfer)- Here we exchange the data between application using JSON
(JavaScript Object Notation) object. The content of JSON object stored as a key value paired. It is easy to
implement web-services using JSON. REST also supports exchanging of data using xml file.
Micro-Services:
Here we break bigger application into smaller mini project and then we establish the communication between these
application using web-services.
Monolithic application: - Here we put all the code in one place and then we host that on the same server.
Singleton Design Pattern: - Here we create a class such that only one object of that class can be created
throughout the execution.
The controller Layer: - is a protocol interface which exposes application functionality as RESTful web services. The
repository layer: - abstracts persistence operations: find (by id or other criteria), save (create, update) and delete
records.
The service layer: - contains our business logic. It defines which functionalities we provide, how they are accessed,
and what to pass and get in return.
Q. What is RESTful web services?
Ans: - In web service we have one type Rest that one is called as RESTful web service Q.
Explain @RestController annotation in Sprint boot?
Ans: - It is a combination of @Controller and @ResponseBody, used for creating a restful controller. It converts the
response to JSON or XML. It ensures that data returned by each method will be written straight into the response body
instead of returning a template.
JPA Annotation:
@Entity: - @Entity help us to map the java class with database table.
@Table: – When java class name and database table name are not same then we use it to map.
@Id: - @Id maps the entity class variable with primary key column of database.
@GeneratedValue: - @GeneratedValue helps us to auto-increment the value while storing the data in the
database.
@Column: - When the entity class variable name and the database column name are not same then this annotation
help us to map it.
Get Post
1.Should be used when getting data from database. 1.Post should be used submitting a dada in database.
2.Submitted data expose in url. 2.Submited data is not expose in url.
3.URL data is safe in browser history. 3.URL data is not safe in browser history.
4.Upon refreshing page we do not get security pop-up 4.Upon refreshing page we get security pop-up alert.
alert. 5.It is more secure.
5.It is less secure.
Ans: - Postman is one of the most popular software testing tools which is used for API testing.
• With the help of this tool, developers can easily create, test, share, and document APIs.
• This tool help as the ability to make various type of http request like GET, POST, PUT, PATCH and convert
the API to code for language like JavaScript and python.
8. What are starter dependencies?
Ans: -Spring boot starter is a maven template that contains a collection of all the relevant transitive
dependencies that are needed to start a particular functionality. Like we need to import spring-boot-starter-web
dependency for creating a web application.
Q. Dependency injunction.
Ans: - Spring boot ideally creates object during runtime and this object address injected to reference variable. This technique
is called as Dependency Injection.
• Setter injection: - The IOC container will inject the dependent bean object into the target bean
object by calling the setter method.
• Constructor injection: - The IOC container will inject the dependent bean object into the target
bean object by calling the target bean constructor.
• Interface injection: - The IOC container will inject the dependent bean object into the target bean
object by Reflection API.
Hibernate Question
1) What is hibernate?
Ans: - Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate, and retrieve data from
the database.
2) What is ORM?
Ans: - ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data
stored in the database. It simplifies data creation, data manipulation, and data access.
1. You don't need to learn SQL 2. Database independent 3. Simple to write a query 5)
What is Session Factory?
Ans: -Session Factory provides the instance of Session. It is a factory of Session. It holds the data of second level cache
that is not enabled by default.
6) What is Session?
It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(),
load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return these instances.
1.There is one session factory object per application. 1.There is one session object per client.
2.Used for creation and management and it is 2.Session is not thread safe and give interface to the
thread safe. mapped classes.
• Configuration • SessionFactory
• Session • Query
• Criteria
• Transaction
Ans: - The SQL query is created with the help of the following syntax: Session.createSQLQuery.
Ans: - The HQL query is created with the help of the following syntax: Session.createQuery.
1)JAP is responsible for managing relation database in java 1)Hibernate is ORM tool used for saving the state of the
application. java object in the database.
2)It is defined under the java.persistence package. 2)It is defined under org.hibernate package.
3)JPA is the java specification and not the implementation. 3)Hibernate is an implementation of JPA and uses common
standard of java persistence API.
4)It is the standard API that allow developer to perform
database operations smoothy. 4) It is used to map java data type with database table and
SQL data type.
5)It uses the entityManagerFactory interface to interact
with the entity manager factory for the persistence unit. 5)It uses the session Factory interface for creating session
instance.
Get () Load ()
1)Get method of hibernate session returns null if object 1)Load method throws objectNotFound exception if
is not found in cache as well as on database. object is not found on cache as well as on database but
never return null.
2. It returns the real object, not the proxy. 2. It returns proxy object
Ans: - If you mark a class as mutable="false", the class will be treated as an immutable class. By default, it is mutable="true".
15) What is the difference between first level cache and second level cache?
1) First Level Cache is associated with Session 1) Second Level Cache is associated with SessionFactory
2) It is enabled by default
2) It is not enabled by default
MYSQL QUESTION
1) What is the different between delete, truncate and drop?
2) What is the different between the primary and unique key in MySQL?