Core Java Interview Questions Answer
Core Java Interview Questions Answer
Core Java Interview Questions Answer
4. OOP Concepts
Object-Oriented Programming (OOP) concepts include:
5. SOLID Principles
Single Responsibility Principle: A class should have one, and only one, reason
to change.
Open/Closed Principle: Software entities should be open for extension but
closed for modification.
Liskov Substitution Principle: Subtypes must be substitutable for their base
types.
Interface Segregation Principle: No client should be forced to depend on
methods it does not use.
Dependency Inversion Principle: Depend on abstractions, not concretions.
6. Design Patterns
Design patterns are standard solutions to common problems in software
design. Examples include:
9. Diamond Problem
The diamond problem occurs in languages that support multiple inheritance
(e.g., C++). It arises when a class inherits from two classes that both inherit
from a common superclass, leading to ambiguity. Java avoids this problem
by not supporting multiple inheritance with classes; instead, it supports
multiple inheritance through interfaces.
Fail-Fast Iterator
Behavior: Fail-fast iterators immediately throw a
ConcurrentModificationException if they detect any structural modification to
the collection after the iterator is created, except through the iterator's own
remove or add methods.
Use Case: Useful when you want to detect bugs early during the
development phase. If a collection is modified while it is being iterated, it’s
often a sign of a concurrency issue or a programming error.
Examples: Iterators of most of the collection classes in java.util package,
such as ArrayList, HashMap, etc.
Implementation: Typically implemented by keeping a modification count
(modCount). The iterator checks this count during each iteration and throws an
exception if it has changed unexpectedly.
Fail-Safe Iterator
Behavior: Fail-safe iterators do not throw ConcurrentModificationException if
the collection is modified while being iterated. They work on a clone of the
collection, hence they are not affected by modifications.
Use Case: Useful in concurrent programming where collections may be
modified by multiple threads simultaneously. They provide a "snapshot" view
of the collection at the time the iterator was created.
Examples: Iterators of the concurrent collections in the
java.util.concurrent package, such as CopyOnWriteArrayList,
ConcurrentHashMap, etc.
Implementation: These iterators typically work on a copy of the collection’s
data, so changes to the collection after the iterator is created do not affect
the iteration.
Comparison Table
Feature Fail-Fast Iterator Fail-Safe Iterator
Exception on Yes
modification (ConcurrentModificationException) No
Underlying collection Iterates over the original collection Iterates over a copy or snapshot
Not suitable for concurrent
Concurrency modifications Suitable for concurrent modifications
CopyOnWriteArrayList,
Examples ArrayList, HashMap, LinkedList ConcurrentHashMap
Performance Typically faster (no need to copy) Typically slower (due to copying)
Conclusion
Fail-Fast Iterators: Good for detecting concurrent modifications during
development and debugging.
Fail-Safe Iterators: Better for scenarios where collections are frequently
modified by multiple threads, providing thread safety and consistency.
BlockingQueue in Java
BlockingQueue is a type of queue in Java that supports operations that wait
for the queue to become non-empty when retrieving an element, and wait
for space to become available in the queue when storing an element. It is
part of the java.util.concurrent package and is designed for use in
concurrent programming.
Key Features
1. Thread Safety: BlockingQueue implementations are thread-safe, meaning
multiple threads can work with the queue without corrupting the data
structure.
2. Blocking Operations: Provides blocking methods such as put() and take()
that wait for the queue to be non-full or non-empty respectively.
3. Timeout: Offers timed versions of these operations, such as offer(e,
timeout, unit) and poll(timeout, unit), which wait for a specified time
before giving up.
4. Bounded and Unbounded: Can be bounded (with a capacity limit) or
unbounded (no capacity limit).
Methods in BlockingQueue
Adding Elements:
void put(E e): Inserts the specified element into the queue, waiting if
necessary for space to become available.
boolean offer(E e, long timeout, TimeUnit unit): Inserts the specified
element into the queue, waiting up to the specified wait time if necessary for
space to become available.
Removing Elements:
E take(): Retrieves and removes the head of the queue, waiting if necessary
until an element becomes available.
E poll(long timeout, TimeUnit unit): Retrieves and removes the head of the
queue, waiting up to the specified wait time if necessary for an element to
become available.
Non-blocking Operations:
boolean offer(E e): Inserts the specified element into the queue if it is
possible to do so immediately without violating capacity restrictions.
E poll(): Retrieves and removes the head of the queue, or returns null if the
queue is empty.
Common Implementations
1. ArrayBlockingQueue: A bounded blocking queue backed by an array. The
capacity is fixed and set at creation time.
2. LinkedBlockingQueue: An optionally bounded blocking queue backed by
linked nodes. If no capacity is specified, it will be effectively unbounded.
3. PriorityBlockingQueue: An unbounded blocking queue that uses the same
ordering rules as PriorityQueue. Elements are ordered according to their
natural ordering or by a comparator provided at queue construction time.
4. DelayQueue: A time-based scheduling queue where elements can only be
taken when their delay has expired.
5. SynchronousQueue: A blocking queue in which each insert operation must
wait for a corresponding remove operation by another thread, and vice
versa. It does not have any internal capacity, not even a single element.
Use Cases
Producer-Consumer Problem: BlockingQueue is particularly useful in the
producer-consumer pattern where producer threads produce data and put it
into the queue, and consumer threads consume data from the queue.
Task Scheduling: Can be used to schedule tasks that should be executed
after a certain delay or at a certain time.
Multithreading: Useful in multithreaded applications to manage the flow of
data between threads safely.
Example: Think of a string like a piece of paper with text written in ink.
Once written, you cannot change the ink. If you want to change the text, you
write it on a new piece of paper.
Why: Private methods belong only to the class they are defined in, while
static methods belong to the class itself, not to instances of the class.
Overriding concerns instance methods.
Example:
java
Copy code
class SuperClass { static void display() { System.out.println( "SuperClass" ); } } class
SubClass extends SuperClass { static void display()
{ System.out.println( "SubClass" ); } } public class Test { public static void main(String[]
args) { SuperClass.display(); // Outputs "SuperClass" SubClass.display(); // Outputs
"SubClass" } }
System.exit() is called.
The JVM crashes.
The thread executing the finally block is interrupted or killed.
Example:
java
Copy code
try { int division = 10 / 0 ; } catch (ArithmeticException e)
{ System.out.println( "Exception caught" ); } finally { System.out.println( "Finally block
executed" ); }
php
Copy code
Exception caught Finally block executed
toString()
equals(Object obj)
hashCode()
clone()
getClass()
notify()
notifyAll()
wait()
finalize()
9. How can you make a class immutable?
To make a class immutable:
Example:
java
Copy code
public final class ImmutablePerson { private final String name; private final int age;
public ImmutablePerson(String name, int age) { this .name = name; this .age = age; }
public String getName() { return name; } public int getAge() { return age; } }
Unchecked Exceptions:
Example:
java
Copy code
try { // code that may throw multiple exceptions } catch (IOException e) { // handle
IOException } catch (SQLException e) { // handle SQLException } catch (Exception e) { //
handle any other exceptions }
java
Copy code
public void method1() throws IOException { method2(); } public void method2() throws
IOException { // code that may throw IOException }
throw keyword:
throws keyword:
Used in method signatures to declare that a method can throw one or more
exceptions.
It does not throw an exception itself, but indicates that exceptions can be
thrown by the method.
Example:
java
Copy code
public void readFile() throws IOException { // method code }
1. Same Exception:
If the superclass method declares an exception, the overridden method in
the subclass can declare the same exception.
java
Copy code
2. Subclass Exception:
Copy code
3. No Exception:
Copy code
4. Unchecked Exceptions:
Copy code
This is one of the first and most frequently asked questions in most of the interviews.
JDBC stands for Java Database Connectivity. As its name implies, it is a Java API used
for interacting with relational databases to access, modify and process data using SQL.
It utilizes JDBC drivers for interacting with the database. By using JDBC, one can
access tabular data from different types of relational databases such as
MySQL, Oracle, MS Access, and so on.
2. What is ResultSet?
The java.sql.ResultSet interface is used to represent the database result set, which is a
result of the execution of SQL queries using statement objects. The object of ResultSet
comprises a cursor that points to the present row of data in the result set. At first, the
cursor is displayed before the first row. Then the cursor moves to the next row by
executing the next() method. The next() method iterates through the result set with the
support of a while loop. If there are no other rows left, the next() method returns a false.
Following is an example for the creation of ResultSet:
ResultSet rs = con.executeQuery(sqlQuery);
No, you can never get null Resultset(). The ResultSet.next() can return null only if the
next record does not comprise a row.
In a ResultSet() handle that is linked to a database, you cannot make the Result a
serialized object. Thus, you cannot pass Resultset() across the network. The RowSet()
spreads the ResultSet() interface, so it comprises all methods from ResultSet().
A RowSet() is always serialized. Thus, we can pass a Rowset() from one class to
another class as it is not connected to the database.
A JDBC driver establishes a connection to the database. It also executes the protocol
for sending the query and result between the database and the client.
The JDBC DriverManager is a static class in Java, using which you operate on the set
of JDBC drivers available for an application to use. Different JDBC drivers can be used
simultaneously by one application if required. Every application specifies a JDBC driver
by using a Uniform Resource Locator (URL). On loading the JDBC Driver class into an
application, it registers itself to the DriverManager by using
DriverManager.registerDriver() or Class.forName(). To confirm this, you can view the
source code of JDBC Driver classes. On calling the DriverManager.getConnection()
method by passing details related to the database configuration, the DriverManager
utilizes the registered drivers to receive the connection and return it to the caller
program.
JDBC-ODBC Bridge: JDBC-ODBC bridge acts as an interface between the DB server and
the client.
Native API: Half Java Driver: This driver almost behaves as a JDBC-ODBC driver. However,
instead of an ODBC driver, you use native APIs and a client-side database.
Network Protocol: This driver works like a 3-tier approach for accessing the database. An
intermediate server connects to the database. The JDBC method calls send data to a
transitional server and then the server communicates with the database.
Thin Driver: It is completely written in Java. This driver explicitly changes JDBC method calls
to the vendor-specific database protocol.
8. Explain which is the most commonly used and fastest JDBC driver.
The JDBC Net pure Java driver (Type 4 driver) is the fastest and most commonly used
driver for remote and localhost connections. It interacts directly with the database by
changing the JDBC calls into vendor-specific protocol calls.
9. What are the data types used for storing images and files in the database
table?
The BLOB data type stores images in the database. You can also store audio and videos
using this data type. This data type stores a binary type of data.
The CLOB data type stores files in the database. This data type stores the character type of
data.
10. Explain what DatabaseMetaData is and why would you use it?
JDBC drivers are developed using the Java Most of the ODBC Drivers have
language. been developed using native
languages such as C, C++
A RowSet is nothing but an object that captures a row set from either tabular data
sources or JDBC result sets such as spreadsheets or files. It supports component-
based development models such as JavaBeans, with the help of event notifications and
a standard set of properties.
The java.sql.ResultSet interface is nothing but the result set of a SQL query. It indicates
that a cursor is pointing to a row of a table.
TYPE_SCROLL_INSENSITIVE: The cursor can move either backward or forward, but the
cursor is not sensitive to changes to the data that underlies the ResultSet.
TYPE_SCROLL_SENSITIVE: The cursor can move backward and forward, but it is sensitive
to the data that underlies the ResultSet.
Note: If we do not declare any ResultSet then this means that we are calling the
TYPE_FORWARD_ONLY ResultSet.
Statement: Executes an SQL query (static SQL query) against the database.
Prepared Statement: Executes an SQL statement repeatedly. The input data is dynamic and
takes the input at the run time.
This is another one of the popular JDBC interview questions. Connection pooling is the
technique by which we reuse the resource-like connection objects that are required to
establish a connection with the database. It is a technique of managing and creating a
pool of connections that can be used by any thread that requires them. Each time an
application tries to access a backend store (such as a database), it needs resources to
develop, maintain, and release a connection to that datastore. Thus, connection pooling
can greatly increase the performance of a Java application while reducing the overall
resource usage.
There are two kinds of architecture models to access the database while using JDBC.
They are:
Two-tier Architecture: In this model, Java programs exclusively connect with the database
and there is no requirement of any mediator like applications servers to connect with the
database. This model is also known as the client-server architecture.
JDBC API
JDBC-ODBC Bridge
Following are the 6 basic steps to connect with the database in Java.
5. Execute the statement object and return a query ResultSet(). Then process the ResultSet().
While this question is not related to JDBC directly, it may still be asked in an interview.
The cold back is the backup process in which the backup of files is taken before
restarting the database. In the hot back, backup process the backup of tables and files
is taken at the time when the database is running.
There are 2 types of locking available in JDBC by which we can manage various user
issues. If two users are trying to access the same record then there is no issue but the
problem arises when multiple users are trying to update the same record
simultaneously. To address this issue, there are two locking modes available in JDBC.
They are:
1. Optimistic Locking: Locks the record only when an update is taking place. This kind of
locking does not use exclusive locks while reading.
2. Pessimistic Locking: In this system, the records are locked as the row to update is selected.
No, when using the JDBC-ODBC Bridge, you can open only one Statement object.
25. What are database warnings in JDBC and explain how we can manage
database warnings in JDBC?
The database warning or SQL warning is nothing but the subclass of the SQLException
class. You can manage or handle this warning by using the getWarnings() method on a
statement, connection, and ResultSet.
execute(): The execute() can be used for any type of SQL Query.
27. Explain what you mean by Metadata and also explain why we use it.
Metadata means information about other data. You use metadata to get the database
product version, driver name, the total number of views and tables.
28. Explain why you would use setAutoCommit(false) in JDBC?
6 months
View Program
11 months
View Program
The Prepared statement execution is much faster than direct execution as the
statement is compiled only once. JDBC drivers and Prepared statements are connected
with each other during execution, and there are no connection overheads.
The interfaces and the classes of JDBC API are mentioned below:
Different Interfaces
Connection: Using the getConnection()method, a connection object is created.
Statement: Using the createStatement() method of the connection class, the statement
object is created.
CallableStatement: The stored procedures and functions are called using the
CallableStatement interface.
Different Classes
DriverManager: The class's function is to serve as a gateway between users and drivers.
Blob: The binary term for a huge object. It stands for a set of binary data that is kept together
in the database management system as a single entity.
Statements
Prepared Statements
Collable Statement
The object of java.lang.Class Object is the return type of the Class.forName() method.
We can set a null value to an index using the setNull()method. Below given is the
syntax for the given method:
The Prepared Statement outperforms the statement since the statement must be compiled
each time the code is run, but the PreparedStatement is compiled once and then executed
only at runtime.
Statement can only run static queries, but Prepared Statement can run parameterized
queries.
Every time, the query used in PreparedStatement appeared to be the same. As a result, the
database can reuse the previous access plan, whereas statement inlines the parameters into
the string, so the query does not appear to be the same every time, preventing cache
utilization.
The steps to write and run stored procedures are listed below.
Create the database procedure: You must first build the stored procedure in the
database before you can use it.
The DriverManager class is used as an interface between the users and drivers. It
maintains track of the available drivers and performs the process of connecting a
database to the proper driver.
The table's information, including the total number of columns, column names, column
types, etc., is returned via the ResultSetMetaData interface.
We can run many queries by utilizing JDBC's batch processing method. It speeds up
the performance. Batch processing is supported through java.sql.Statement and
java.sql.Prepared Statement interfaces. The actions listed below are necessary for
batch processing in JDBC.
Create Connection
Create Statement
Close Connection
BLOB: A BLOB is a big, variable-length binary object that is used to store mixed media,
voice, and other binary data types. On a MySQL database, it can hold up to 2GB of
data, and on an Oracle database, up to 128 GB. Many databases, including MySQL,
Oracle, and DB2, enable BLOB to store binary data (images, video, audio, and mixed
media).
The four different types of locks offered by JDBC are discussed below.
Row and Key Locks: We utilize this kind of lock when updating the rows.
Page locks: A page can have one of these locks applied to it.
Database locks: When a database is open, a lock is used to stop other transactions from
reading or updating data.
46. How can we store and retrieve images from the database?
We may store and retrieve photos using the Prepared Statement interface. A table with
the columns NAME and PHOTO should be created.
CLOB datatype is used in the table to store files in the Oracle database.
To retrieve the file in the Oracle database we use the getClob() method of the prepared
statement.
Will not have the return type Will have the return type.
It supports both input and output parameters It supports only one parameter.
6 months
View Program
11 months
View Program
Using setMaxRows(int i), we can limit the number of rows returned by a database using
the query. Since MySQL allows us to use the limit cause, this may also be done within
the query.
Serialization in Java is a process that allows an object to be converted into a byte stream, thereby
making it possible to save the object to a file, send it over a network, or store it in a database.
This process allows for the object's state to be preserved and later reconstructed when needed,
through a process known as deserialization.
1. Serializable Interface: For an object to be serialized, its class must implement the
java.io.Serializable interface. This is a marker interface, meaning it does not
contain any methods but serves to indicate that a class can be serialized.
2. Serialization Process: The process of serialization is typically handled by the
ObjectOutputStream class. This class has methods like writeObject() which are used
to serialize an object.
java
Copy code
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("object.ser"));
out.writeObject(myObject);
out.close();
java
Copy code
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("object.ser"));
MyClass myObject = (MyClass) in.readObject();
in.close();
4. Transient Keyword: Fields marked with the transient keyword are not serialized. This
can be useful for fields that are sensitive or do not need to be saved.
java
Copy code
private transient int temporaryData;
5. serialVersionUID: This is a unique identifier for each class that is used during the
deserialization process to ensure that a loaded class corresponds exactly to a serialized
object. If the class does not have a matching serialVersionUID, an
InvalidClassException will be thrown.
java
Copy code
private static final long serialVersionUID = 1L;
java
Copy code
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
// custom serialization code
}
Advantages of Serialization:
Serialization is a powerful feature in Java, but it should be used with an understanding of its
implications and best practices to avoid common pitfalls.
4o
Q12 – How to make class serilizable ?
java
Copy code
import java.io.Serializable;
2. Define a serialVersionUID Field: This is a unique identifier for each class that aids in
version control during the deserialization process. It helps ensure that a loaded class
corresponds exactly to a serialized object. If you do not define it, Java will generate one
automatically, which can lead to compatibility issues if the class definition changes.
java
Copy code
private static final long serialVersionUID = 1L;
3. Mark Non-Serializable Fields as transient: If there are fields in your class that should
not be serialized (e.g., sensitive information, temporary data), mark them with the
transient keyword.
java
Copy code
private transient int temporaryData;
java
Copy code
import java.io.Serializable;
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
Customizing Serialization
If you need to customize the serialization process, you can provide your own implementations of
the writeObject and readObject methods. This is useful if you have special requirements for
how your object should be serialized and deserialized.
java
Copy code
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
writeObject method is used to write the default fields and then manually serialize the
salary field.
readObject method is used to read the default fields and then manually deserialize the
salary field.
Example Usage
Here's an example of how you might serialize and deserialize an Employee object:
java
Copy code
import java.io.*;
Serializable Interface
1. Marker Interface: Serializable is a marker interface, meaning it does not contain any
methods. It signals to the Java runtime that objects of the implementing class can be
serialized and deserialized.
2. Default Serialization: When a class implements Serializable, Java handles the
serialization process automatically using reflection. The default serialization mechanism
serializes the entire object graph, which can be convenient but may not be efficient or
flexible.
3. Customization: Customization of the serialization process can be achieved by
implementing the writeObject and readObject methods within the class. These
methods allow for fine-grained control over what data is serialized and how it is
serialized.
java
Copy code
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
// Custom serialization code
}
4. Transient Keyword: Fields marked with the transient keyword are not serialized. This
is useful for fields that contain sensitive or temporary data.
Externalizable Interface
java
Copy code
public class MyClass implements Externalizable {
private String name;
private int age;
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeInt(age);
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
name = (String) in.readObject();
age = in.readInt();
}
}
Comparison Summary
Serializable: Use this when you want a simple way to serialize objects with minimal
code and default behavior is sufficient. It is easier to implement and requires less
boilerplate code.
Externalizable: Use this when you need full control over the serialization process, want
to optimize the serialized data format, or need to implement a custom serialization
mechanism for complex objects. It offers greater
The main goal of serialVersionUID is to ensure that an object's sender and receiver
have loaded classes for it. These classes are compatible with serialization. If this is
not the case, then an InvalidClassException exception will occur.