JAVA Interview Question NEW 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

CORE JAVA INTERVIEW QUESTIONS

1. Explain the main method of the class ? ( psvm() )


Ans- Args in main method is a variable which is a user defined. It is a method argument of the type array and it can
have any name.
String args in main method is used to receive command line arguments.

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.

2. Difference between Static , Non – static , Local variables ? Ans-

Static Variable Non-Static Local Variable

Static Variables can be accessed


Non-static variables can be
using class name. accessed using instance of a class. A variable declared inside the body
of the method is called local variable.

Static variables can be accessed by Non-Static variables cannot be


static & non-Static method accessed inside a static method. We can use this variable only
within that method.

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.

 Var types in Java ?


I. Var types was introduces in version 10 in java.
II. A variable of the types var can store any kind of value in it. III. Var is not a keyword.

Difference between JDK and JRE ?


Ans- JDK - It helps us to compile .java file to
.class file. JRE - JRE helps us to run .class file.

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.

5. Explain about Constructor overloading , Constructor chaining , Default Constructor ?


Ans- Constructor Overloading: Here we create more than one constructor in the same class provided that
they have different number of arguments or different types of arguments.

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.

6. What is this keyword ?


Ans- This Keyword is a special reference variable that holds object address. This keyword creates automatically.
This keyword points to current object running in the program.
We cannot use This keyword inside static method. Using This keyword we can call constructor.

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.

8. Explain about OOPS concept ?(Inheritance , Polymorphism , Abstraction , Encapsulation )


Ans- Object-Oriented Programming System (OOPs) is a programming concept that works on the principles of abstraction,
encapsulation, inheritance, and polymorphism. It allows users to create objects they want and create methods to
handle those objects. The basic concept of OOPs is to create objects, re-use them throughout the program, and
manipulate these objects to get results.
Abstractions: Hiding of implementation details is called as abstraction. The way we achieve this in java is by using
interface and abstract class
 Abstract Keyword:- When applied on a method it defined method in a incomplete interface we can create
incomplete method even without using abstract keyword. That means uses of abstract keyword is optional.
Encapsulation: Bundling of data with methods which operate on that data avoiding direct access to the variable is
called Encapsulation.
Inheritance: Here we inherit the member from parent class to child class with an intension of reusing it.
Polymorphism: Here we can develop a feature in a way that it can take more than one form. Polymorphism
is applicable only on method.
 There are two way we can achieves polymorphism.
 Overriding :- Here we inherit the method from parent class and modify its logic in child class by once again
creating same method in child class.
 Overloading :- Developing more then one method in the same class provide they have different number of
arguments or different types of arguments then it is called as overloading.

9. Explain about Type casting and Class casting ?


Ans- Converting particular data type into required data type is called as type casting.
There are two types- I.
Auto Up casting
II. Explicit Down casting Class Casting are
of two types:
i)Class Up Casting: Here we store child class object address into parent class reference variable.
ii)Class Down Casting: Here we store parent class object address into child class reference variable.
10.What is run - time polymorphism ?
Ans- In run-time-polymorphism we perform overriding with class upcasting.
11.Explain about Interfaces ?
Ans- Interface can consist of only incomplete method in it. Interface is 100% incomplete method. Interface support
multiple inheritance. Every variable in an interface is static and final. An interface can consist of main method in
version 8 of java onward.

12.Explain all access specifiers ? ( public , private , protected , default )


Ans- Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the
class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child class.
If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class,
within the package and outside the package. 13. What is final keyword ? Ans- If we make variable final then
its value cannot be changed.
• If we make static/no-static variable final then initialization is mandatory.
• If we make a method final then overriding is not allowed.
• If we make class as final then inheritance of that class is not allowed.

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.

15.Explain about abstract class ? Ans- An abstract class can


consist of both complete and incomplete method.
• To define incomplete method in abstract class usage of abstract keyword is mandatory.
• In an abstract class, we can create main method.
• Creating object in abstract class is not allowed.
• Abstract classes do not support multiple inheritances.
• In an abstract class we can create static variable as well as no static variable.

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.

18.Explain about Serialization and de-Serialization ?


Ans- Serialization:- Here we convert the object 0’s to 1’s then it stores the object states permanently stores.
Deserialization:- Here we read the file content and then we found the back on object back on RAM.

19.What is Transient keyword ?


Ans- During the serialization, when we do not want an object to be serialized we can use a transient keyword.
20.Explain about mutable and immutable ?
Ans- Mutable: Mutable is something wherein the class object properties keeps on changing.
Immutable: Immutable class once its object is created then its state can not be alter.

21.Why String is immutable ?


Ans- A String is an unavoidable type of variable while writing any application program. String references are used to
store various attributes like username, password, etc. In Java, String objects are immutable. Immutable simply means
unmodifiable or unchangeable.

22.How to create immutable class ?


Ans- Steps to create immutable class:
-create a final class.
- Set the values of the properties using only constructor.
- Make the properties as final
-Do not provide any setters for these properties.

23.Explain about String constant pool ?


Ans- The area where these immutable objects are being created that area is called as String Constant Pool.
24.Difference between String , String Buffer , String Builder ? Ans- The String class is an immutable class
whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and
StringBuilder such as -

String Buffer String Builder


StringBuffer is synchronized i.e. thread safe. It means two StringBuilder is non-synchronized i.e. not thread safe. It
threads can't call the methods of StringBuffer means two threads can call the methods of StringBuilder
simultaneously. simultaneously.

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

25.Difference between == and .equals() method ?


Ans- The main difference between the .equals() method and == operator is that one is a method, and the other is
the operator. We can use == operators for reference comparison (address comparison) and .equals() method for
content comparison.

26.Difference between continue and break statements.


Ans-Break Statement:- Break Statement is used to "jump out" of a switch statement. The break statement can also
be used to jump out of a loop.
Continue Statement:- The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

27.What is ternary operator ?


Ans- In Java, the ternary operator is a type of Java conditional operator. The ternary operator consists of three
operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the
variable. It can be used instead of the if-else statement. It makes the code much more easy, readable, and shorter.

28.Difference between Array and vector ?


Ans- ArrayList and Vector both implements List interface and maintains insertion order.

ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.

ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized


ArrayList increments 50% of current array size if the Vector increments 100% means doubles the array size if

number of elements exceeds from its capacity. the total number of elements exceeds than its capacity.

29.Explain about increment and decrement operators ?


Ans- In java, increment decrement operators is also known as unary operator. It is used to represent the positive or
negative value, increment/decrement the value by 1 and complement a Boolean value.

30.What are Threads ?


Ans- Multi-tasking done at program level is called as threads.
The main purpose of thread is to improve the performance of the application by reducing time. There
are two ways we can build threads: i)Build-in thread ii)User-defined thread

31.How many ways we can create threads ?


Ans- There are two ways we can build threads:
i)Build-in thread
ii)User-define thread

32.What are runnable interfaces and callable interfaces?


Ans- Callable interface and Runnable interface are used to encapsulate tasks supposed to be executed by another
thread.

Runnable Interface Callable Interface


It cannot return the return of computation. It can return the result of the parallel processing of a

task.

It cannot throw a checked Exception. It can throw a checked Exception.

In a runnable interface, one needs to override the run() In order to use Callable, you need to override the call()

method in Java.

33.What is Synchronization , advantages and disadvantages?


Ans- When two threads are operating on common data, the data might get corrupted because of multi-tasking.
To make thread operate one after another, we use synchronize keyword wherein the thread has acquired the lock
can only execute the block where as other thread would be in wait status.
Only when the first thread release the lock the other thread will get the opportunity to acquire the lock and execute
the block.

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.

36.What is Thread pool , join thread , detach?


Ans- Thread pool are useful when is needed to limit the number of threads running in our application at the same
time. This will help us to improve the performance of the application.
Instead of starting new thread for every task execute can currently, the task can be passed to a thread pool. A thread
pool contain collection of threads as soon as the pool has an ideal thread, the task is assign to one of them and
execute. Threads pool are often used in server. Each connection arriving at server via network is rapped as task and
passed on a thread pool. The thread in thread pool will process the request on the connection concurrently. This is
how we can use existing thread instead of creating new thread and there by improve the performance in term of
execution.
37.What are Enum , Wrapper , optional , local , anonymous ?
Ans- Enum: Enum is collection of constant.
Wrapper: The processing of storing the value inside an object is called as Wrapping or boxing.
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent
value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead
of checking null values.
Optional: A variable declared inside the body of the method is called local variable. We can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
Anonymous :A class that has no name is known as an anonymous inner class in Java. It should be used if we have to
override a method of class or interface.

38.Explain about final , finally , finalize ?


Ans- Final: Final is a keyword which means if we make a variable as final then its value can’t be change. If we make
static non-static variable as final then initialization is mandatory. If we make method as final then overriding is not
allowed. Same as if we make class as final then inheritance is not allowed.
Finally: Finally is an extension of try catch block. Regardless of exception happens or not finally will execute. We can
also write only try and Finally.
Finalize: Finalize is method present inside object class. Garbage collection logic is implemented in finalized method.

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.

40.What are regular expressions in java ?


Ans- A regular expression is a sequence of characters that forms a search pattern. When we search for data in a text,
we can use this search pattern to describe what we are searching for. A regular expression can be a single character,
or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace
operations.

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.

47.Difference between Array list and Linked list , vectors? Ans-


ArrayList LinkedList Vectors

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.

48.How to find the length of the list ? ( .size() )


Ans - The size() method of List Interface returns the total number of elements present in this list. The size() method
returns the number of elements in this list.
49.Explain about hash table ?
Ans- HashTable is an associated array where in the value store as a key value pair.
Initial size of a hashtable is 16 byte when load ratio becomes 75% that is out of 16 twelve elements are injected into
the table then the size of table becomes double automatically. HashTable is Synchronized.

50.What is hashing technique ?


Ans- Hashing is a technique where we are representing any entity in the form of integer and it is done in java using a
hashcode method. 51. What is collision ? Ans- When two values are being store in the same index number then it is
called as collision. To solve this problem in hashtable we store the data as list mapped to the same index number.

52.Explain about Set interface ?


Ans- Set is an interface and does not maintain any insertion order. It can’t contain duplicate values.
53.Difference between List and Set ? Ans-
List Set
1. The List is an ordered sequence. 1. The Set is an unordered sequence.
2. List allows duplicate elements 2. Set doesn’t allow duplicate elements.
3. Elements by their position can be accessed. 3. Position access to elements is not allowed.
4. Multiple null elements can be stored. 4. Null element can store only once.

5. List implementations are ArrayList, LinkedList, 5. Set implementations are HashSet,


Vector, Stack LinkedHashSet.

54.Difference between hash set and Tree set ?


Ans-

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.

55.Difference between hash map and concurrent hashmap? Ans-

HashMap Concurrent HashMap


Hashmap is not synchronized. Concurrent Hashmap is synchronized.
In HashMap, threads are not safe. In concurrent hashmap, threads are safe.
It do not allows to store null keys/values.
It allows for storing null keys and values. It is slower than Hashmap

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.

57.Difference between Iterator and List Iterator ?


Ans- Iterators are used in Collection framework in Java to retrieve elements one by one. It can be applied to any
Collection object. By using Iterator, we can perform both read and remove operations.
ListIterator is only applicable for List collection implemented classes like arraylist, linkedlistetc. It provides
bidirectional iteration. ListIterator must be used when we want to enumerate elements of List.

58.Difference between Comparator and Comparable ?


Ans-
Comparable Comparator

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.

60.Types of constructor Ans- There are two types of constructors in Java:


i)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.
ii)Parameterized constructor: A constructor which has a specific number of parameters is called a parameterized
constructor. The parameterized constructor is used to provide different values to distinct objects. However, we can
provide the same values also.

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

1.SOAP is a protocol. REST is an architectural style.


2. SOAP stands for Simple Object Access REST stands for REpresentational State Transfer. REST can
use SOAP web services because it is a concept and can
Protocol.
use any protocol like HTTP, SOAP.
3. SOAP can't use REST because it is a protocol.
JAX-RS is the java API for RESTful web services.
4. JAX-WS is the java API for SOAP web services.

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.

76.Difference between Web server and Application server.


Ans- Web Server are responsible to run static application. While Application Server are responsible to run
.
technologies like servlet, jsp, ejp, Spring Boot etc

ADVANCE JAVA QUESTIONS


1. Explain the life cycle of Servlet , JSP ? Ans- Servlet Life Cycle:

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.

HTML: HTML stands for Hyper Text Markup Language


HTML is the standard markup language for creating Web pages
HTML describes the structure of a Web page
HTML consists of a series of elements
HTML elements tell the browser how to display the content

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.

7. Write a logic for JDBS connection?


Ans- Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/web_app_demo_4","root","Shamim@123");
8. Explain about CSS and Java Script ?
Ans- CSS: CSS stands for Cascading Style Sheet, it is a style sheet language used to shape the HTML elements that
will be displayed in the browsers as a web-page. Without using CSS, the website which has been created by using
HTML will look dull. Basically CSS gives the outer cover on any HTML elements. If you consider HTML as a skeleton of
the web-page then the CSS will be the skin of the skeleton.
JavaScript: It is a lightweight, cross-platform, and interpreted scripting language. It is well-known for the
development of web pages. JavaScript can be used for Client-side developments as well as Server-side developments.
JavaScript contains a standard library of objects, like Array, Date, and Math, and a core set of language elements like
operators, control structures, and statements.

9. Explain about JSTL tags ?


Ans- JSTL (JSP Standard Tag Library): The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP
development.
There JSTL mainly provides five types of tags:
i)Core Tag ii)Function Tag iii)Formating Tag
vi)XML Tags v)SQL Tag
10.Different types of creating Sessions? Ans-
11.Explain about request dispatcher ?
Ans- The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html,
servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet
collaboration.
There are two methods defined in the RequestDispatcher interface.
i)Public void Forward ii) Public void include

12.Write SQL queries ?


Ans-
13.What are data types of SQL? Ans- TINYINT – 128 to -128
SMALLINT – 32768 to -32767
MEDIUMINT – 8388608 to -8388608
INT – 2^31-1 Char
– char(4)
Varchar xorch(20)
14.What are constrains?
Ans- SQL constraints are used to specify rules for data in a table. Constraints are used to limit the type of data
that can go into a table. This ensures the accuracy and reliability of the data in the table. i)Not Null - Ensures that a
column cannot have a NULL value ii)Unique- Ensures that all values in a column are different iii)Primary Key- A
combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table iv)Foreign Key- Prevents actions
that would destroy links between tables v) Enum- Gives us a fixed value to be selected. vi)SET- Set is group of
value and this constrain help us to select anyone value from the set.
15.Explain about joins?
Ans- A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
16.Explain about 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.

17.Difference between spring and spring boot?

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.

20.Explain about POSTMAN ?


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.

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.

22.Difference between save and persist method in hibernate ? Ans-


Save () Persist ()

It stores object in database It also stores object in database


It return generated id and return type is serializable It It does not return anything. Its void return type.
can save object within boundaries and outside boundaries It can only save object within the transaction boundaries
It will create a new row in the table for detached object It will throw persistence exception for detached object It
It is only supported by Hibernate is also supported by JPA

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.

Q. Where did you achieved polymorphism?


Ans: - After inheriting incomplete method, I was overriding child class to complete that model and here I achieved
polymorphism.
Q. What is abstraction? Where have you used this in practical?
Ans: - Hiding of implementation details is called as abstraction and the way we achieve this in java is by using
interface and abstract class. In my project, I was developing an interface layer DAOService, where I defined all the
incomplete method and implemented that in the class DAOServiceImpl wherein all database related queries where
written down.
Q. What is Inheritance? Give practical example.
Ans: - Here we inherit the member from parent class to child class with an intension of reusing it. In my project, I
Created an interface DAOService and from here I inherited incomplete method to class DAOServiceImpl. Q. What
are WEB Servers?
Ans- Web Servers are responsible to run static application. Examples of server are –IIS, NGinx, google web server etc.
Q. Where does Maven download the Jar file?
Ans – Maven download the jar file in M2 folder.
Q. What does pom.xml file do?
Ans- pom.xml file instruct Maven Dependencies to download jar file. Q.
From where does Maven download dependencies?
Ans – It has own website called as MVN repository.
Note: Objects in Spring Boot are term as Bean.
Q. Which version of hibernate you were using in your project?
Ans- Hibernate core 5.6v.

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.

Q. What is the difference between @RestController and @Controller in Spring Boot?


Ans: - @Controller Map of the model object to view or template and make it human readable but @RestController
simply returns the object and object data is directly written in HTTP response as JSON or XML
Annotation:

@Autowired: - @Autowired helps us to perform dependency injection.


@Controller: - @Controller helps us to define controller layer in our spring boot application.
@RequestMapping: - @RequestMapping maps form-url with controller method.
@ModelAttribute: - @ModelAttribute maps the form data to entity class object.
@RequestParam: - @RequestParam maps form data with controller method arguments.
@RestController: - @RestController help us to define web-services layer in our project.
@GetMapping: - @GetMapping get all the data from DB and maps it JSON object.
@PostMapping: - @PostMapping maps the JSON object content to DB.
@PutMapping: - @PutMapping help us to update data in DB using web-services.
@DeleteMapping: - @DeleteMapping help us to delete the record in DB using web-services.
@Service: - @Service help us to define service layer in our project.
@Request Body: - It maps JSON object content to java object in webservice.
@Path Variable: - It read data from webservice URL and initializes method argument.

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.

Q. Single ton design pattern.


Ans: - Here be design a class such as that only one object of that class can be created throw-out the program.
Q. Why Spring Boot over Spring?
Below are some key points which spring boot offers but spring doesn’t:
• Starter POM.
• Version Management.
• Auto Configuration.
• Component Scanning.
• Embedded server.
• InMemory DB.
• Actuators

Q. Different between Spring and Spring boot.


Spring Spring Boot
1.Configuration need to be done using xml file. 1.It is east to do configuration because of application
properties files.
2.Initial dependency need to be downloaded
separately. 2.Initial dependency are added up using stater tags.

3.Need to configure tomcat separately. 3.It has embedded Tomcat.

Q.What is the difference between RequestMapping and GetMapping?


Ans: - RequestMapping can be used with GET, POST, PUT, and many other request methods using the method attribute on the
annotation. Whereas getMapping is only an extension of RequestMapping which helps you to improve on clarity on request. Q.
Spring bean life cycle.
Ans: - Spring container firstly create a bean then perform dependency injunction then once dependency
injunction is done it call init fallowed by utility method. Finally, when destroy method is called the bean life
cycle comes to ends.

Q. What is Spring Security?


Ans: - It helps us to defined security role.
In my project I never implemented this it was already develop by my senior. Q.
Spring IOC.
Ans: - Contain the principle of dependency injunction and complete bean life cycle is maintain in spring IOC. -It
is responsible to create an object and holds it’s in the memory.
Q. Spring initialize
Ans- Spring Initializer is a web-based tool provided by the Pivotal Web Service. With the help of Spring Initializer, we
can easily generate the structure of the Spring Boot Project. It offers extensible API for creating JVM-based projects.

Q. Different between Get and Post method in java?

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.

Q. Explain about POSTMAN?

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.

There are 3 ways to perform decency 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.

3) What is HQL (Hibernate Query Language)?


Ans: - Hibernate Query Language is known as an object-oriented query language. It is like a structured query language
(SQL).

The main advantage of HQL over SQL is:

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?

Ans: - It maintains a connection between the hibernate application and database.

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.

7) Different between session factory and session.

Session Factory Session

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.

8)What are the core interfaces of Hibernate?

Ans: - The core interfaces of Hibernate framework are:

• Configuration • SessionFactory
• Session • Query
• Criteria
• Transaction

9) How is SQL query created in Hibernate?

Ans: - The SQL query is created with the help of the following syntax: Session.createSQLQuery.

10) How is HQL query created?

Ans: - The HQL query is created with the help of the following syntax: Session.createQuery.

11) How can we add criteria to a SQL query?

Ans: - A criterion is added to a SQL query by using the: Session.createCriteria.

12) Different between JPA and Hibernate?


JPA Hibernate

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.

13) Different between Get and load method in hibernate.

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

14 How to make an immutable class in hibernate?

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?

First Level Cache 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?

Delete Truncate Drop


1.It remove some or all rows 1.It remove all row from a table. 1.It remove a table from the
from a table. 2.Truncate cannot be used with database.
2.It remove row one by at a indexed views. 2.All tables, rows, indexes and
time. 3.It is performance wise faster. privileges will also be removed
3.It can be used with indexed when used this command.
views. 3.The operation cannot be
rolled back.

2) What is the different between the primary and unique key in MySQL?

Primary Key Unique Key


1.A table can hold only one primary key. 1.It can be more than one unique key in one
2.A Primary key cannot be null. table.
2.A unique key can have null.

You might also like