Interview Questions On JAVA
Interview Questions On JAVA
1. What is JAVA?
Java is a high-level programming language and is platform-independent.
Java is a collection of objects. It was developed by Sun Microsystems.
2. What are the features of JAVA?
a) OOP concepts:
Object-oriented
Inheritance
Encapsulation
Polymorphism
Abstraction
b) Platform independent: A single program works on different platforms without any
modification.
c) High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT
converts the bytecode into machine language and then JVM starts the execution.
d) Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which
is called the main thread. The user can create multiple threads by extending the thread class
or by implementing the Runnable interface
6- No Unsigned Types Unlike C/C++, Java does not support unsigned int, unsigned char, etc.
However, in Java 8, API for unsigned long and unsigned int is introduced
Local variables are defined in the method and scope of the variables that exist inside the
method itself.
Instance variable is defined inside the class and outside the method and the scope of the
variables exists throughout the class.
String variables are stored in a “constant string pool”. Once the string reference changes the
old value that exists in the “constant string pool”, it cannot be erased.
String Buffer:
Here string values are stored in a stack. If the values are changed then the new value replaces
the older value.
The string buffer is synchronized which is thread-safe.
Performance is slower than the String Builder.
String Builder:
This is the same as String Buffer except for the String Builder which is not threaded safely
that is not synchronized. So obviously the performance is fast.
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn
more about in the next chapter).
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must
be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
Implementation:
Notes on Interfaces:
• Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
• Interface methods do not have a body - the body is provided by the "implement" class
• On implementation of an interface, you must override all of its methods
• Interface methods are by default abstract and public
• Interface attributes are by default public, static and final
• An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class can implement
multiple interfaces. Note: To implement multiple interfaces, separate them with a comma
15. What is singleton class in Java 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.
Interfaces: These interfaces supply the abstract data type to represent the collection. The
java.util.Collection is the root interface of the framework. It’s at the top of the framework
hierarchy and contains important methods, like size(), iterator(), add(), remove(), and clear().
The iterable interface is the root of the whole collection framework. It allows the iterator to
iterate through all of the collections. All classes and interfaces use this interface. The
collection interface extends the iterable interface and is executed by the classes in the
collection framework. The list interface inhibits a list type data structure where we can store
ordered collections of objects.
Java collections: List
A List is an ordered Collection of elements which may contain duplicates. It is an interface
that extends the Collection interface. Lists are further classified into the following:
• ArrayList :
• LinkedList
• Vectors
Array list:
• Fast iteration and fast Random Access.
• It is an ordered collection (by index) and not sorted.
• It implements the Random Access Interface.
Linked List:
• Elements are doubly linked to one another.
• Performance is slower than the Array list.
• Good choice for insertion and deletion.
Singly Linked List : In a singly Linked list each node in this list stores the data of the node
and a pointer or reference to the next node in the list. Refer to the below image to get a better
understanding of single Linked list.
Doubly Linked List : In a doubly Linked list, it has two references, one to the next node and
another to previous node.
Vectors :
• Vector methods are synchronized.
• Thread safety.
• It also implements Random Access.
• Thread safety usually causes a performance hit.
Stack:
The stack is a linear data structure that is used to store the collection of objects. It is based on
Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to
store the collection of objects. One of them is the Stack class that provides different
operations such as push, pop, search, etc.
Java collections: Queue
Queue in Java follows a FIFO approach i.e. it orders the elements in First In First Out
manner. In a queue, the first element is removed first and last element is removed in the end.
Each basic method exists in two forms: one throws an exception if the operation fails, the
other returns a special value.
Priority Queue
The Priority Queue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. Priority Queue doesn't allow null values to be
stored in the queue.
Deque Interface:
Deque interface extends the Queue interface. In Deque, we can remove and add the elements
from both the side. Deque stands for a double-ended queue which enables us to perform the
operations at both the ends.
Array Deque
Array Deque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.
Array Deque is faster than ArrayList and Stack and has no capacity restrictions.
Java collections: SET
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
HashSet:
• Unordered and unsorted.
• Uses the hash code of the object to insert the values.
• Use this when the requirement is “no duplicates and don’t care about the order”.
LinkedHashSet:
• An ordered version of the hash set is known as Linked Hash Set.
• Maintains a doubly-Linked list of all the elements.
• Use this when an iteration order is required.
TreeSet:
• It is one of the two sorted collections.
• Uses the “Read-Black” tree structure and guarantees that the elements will be in
ascending order.
• We can construct a tree set with the constructor by using a comparable (or)
comparator.
Java collections: MAP
Map cares about the unique identifier. We can map a unique key to a specific value. It is a
key/value pair. We can search a value, based on the key. Like the set, the map also uses the
“equals ( )” method to determine whether two keys are the same or different.
Hash Map:
• Unordered and unsorted map.
• Hashmap is a good choice when we don’t care about the order.
• It allows one null key and multiple null values.
Hash Table:
• Like the vector key, methods of the class are synchronized.
• Thread safety and therefore slows the performance.
• It doesn’t allow anything that is null.
Linked Hash Map:
TreeMap:
• Sorted Map.
• Like Tree set, we can construct a sort order with the constructor.
3. Contiguous memory locations are usually used for storing actual values in an array
but not in ArrayList. Explain.
An array generally contains elements of the primitive data types such as int, float, etc. In
such cases, the array directly stores these elements at contiguous memory locations. While
an ArrayList does not contain primitive data types. An arrayList contains the reference of the
objects at different memory locations instead of the object itself. That is why the objects are
not stored at contiguous memory locations.
6. ArrayList, LinkedList, and Vector are all implementations of the List interface.
Which of them is most efficient for adding and removing elements from the list?
Explain your answer, including any other alternatives you may be aware of.
Of the three, LinkedList is generally going to give you the best performance. Here’s why:
ArrayList and Vector each use an array to store the elements of the list. As a result, when an
element is inserted into (or removed from) the middle of the list, the elements that follow
must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is
not needed, it is recommended to use ArrayList rather than Vector.
LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an
inserting or removing an element only requires updating the links that immediately precede
and follow the element being inserted or removed.
JAVA EXCEPTION HANDLING
1. What is meant by Exception?
An Exception is a problem that can occur during the normal flow of execution. A method
can throw an exception when something wails at runtime. If that exception couldn’t be
handled, then the execution gets terminated before it completes the task.
Unchecked Exception:
These exceptions are not checked during the compile time by the compiler. The compiler
doesn’t force to handle these exceptions. It includes:
• Arithmetic Exception
• ArrayIndexOutOfBounds Exception
(The ArrayIndexOutOfBounds exception is thrown if a program tries to access an
array index that is negative, greater than, or equal to the length of the array.)
3. What are the different ways to handle exceptions?
a) Using try/catch:
The risky code is surrounded by try block. If an exception occurs, then it is caught by the
catch block which is followed by the try block.
While exceptions are conditions that occur because of bad input or human error etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the cases it
is possible to recover from an exception (probably by giving the user feedback for entering
proper values etc.
a) Extend Thread class: Extending a Thread class and override the run method. The thread
is available in java.lang.thread.
The disadvantage of using a thread class is that we cannot extend any other classes because
we have already extended the thread class. We can overload the run () method in our class.
Based on the above code, the main thread has started the execution. When it reaches the code
t.start() then ‘thread t’ starts the own stack for the execution. JVM switches between the
main thread and ‘thread t’.
Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task, then
only the main thread starts the execution.
It is a non-static method. The Join () method has an overloaded version. So we can mention
the time duration in join () method also “.s”.
4. What does the yield method of the Thread class do?
A yield () method moves the currently running thread to a runnable state and allows the other
threads for execution. So that equal priority threads have a chance to run. It is a static
method. It doesn’t release any lock.
Yield () method moves the thread back to the Runnable state only, and not the thread to sleep
(), wait () (or) block.
Sleep: Sleep () method is used to sleep the currently executing thread for the given amount
of time. Once the thread is wake up it can move to the runnable state. So sleep () method is
used to delay the execution for some period.
It is a static method.
• New: In New state, a Thread instance has been created but start () method is not yet
invoked. Now the thread is not considered alive.
• Runnable: The Thread is in the runnable state after the invocation of the start ()
method, but before the run () method is invoked. But a thread can also return to the
runnable state from waiting/sleeping. In this state, the thread is considered alive.
• Running: The thread is in a running state after it calls the run () method. Now the
thread begins the execution.
• Non-Runnable(Blocked): The thread is alive but it is not eligible to run. It is not in
the runnable state but also, it will return to the runnable state after some time.
Example: wait, sleep, block.
• Terminated: Once the run method is completed then it is terminated. Now the thread
is not alive.
JAVA SYNCHRONIZATION
1. What is Synchronization?
Synchronization makes only one thread to access a block of code at a time. If multiple
threads access the block of code, then there is a chance for inaccurate results at the end. To
avoid this issue, we can provide synchronization for the sensitive block of codes.
The synchronized keyword means that a thread needs a key in order to access the
synchronized code.
Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can
access a synchronized method only if the thread can get the key to the objects to lock.
For this, we use the “Synchronized” keyword.
1. 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.
Interfaces:
• Connection
• Statement
• PreparedStatement
• ResultSet
• ResultSetMetaData
• DatabaseMetaData
• CallableStatement etc.
Classes:
• DriverManager
• Blob
• Clob
• Types
• SQLException etc.
JAVA SPRING
1. What is 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.