Core Java Interview Questions Answer

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

Why is Java a platform-independent language?

Java is considered platform-independent because of its use of the Java Virtual


Machine (JVM). When you compile a Java program, it is converted into
bytecode, which is an intermediate, platform-neutral code. The JVM, which is
platform-specific, reads and executes this bytecode on any device or
operating system. This "write once, run anywhere" capability is a core
feature of Java.

2. Why is Java not a pure object-oriented language?


Java is not considered a pure object-oriented language because it supports
primitive data types (e.g., int, char, float, etc.) that are not objects. In a pure
object-oriented language, everything is represented as objects.

3. Instance Variable vs. Local Variable


 Instance Variable: A variable that is declared inside a class but outside any
method or constructor. It is tied to a specific instance of the class.
 Local Variable: A variable that is declared within a method, constructor, or
block. It is only accessible within that specific method, constructor, or block.

4. OOP Concepts
Object-Oriented Programming (OOP) concepts include:

 Encapsulation: Bundling data with methods that operate on that data.


 Inheritance: Mechanism where one class inherits the properties and
behavior of another.
 Polymorphism: Ability to present the same interface for different data
types.
 Abstraction: Hiding complex implementation details and showing only the
necessary features.

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:

 Creational Patterns: Singleton, Factory, Builder, Prototype.


 Structural Patterns: Adapter, Composite, Proxy, Flyweight.
 Behavioral Patterns: Strategy, Observer, Command, State.

7. Access Modifiers in Java


 private: Accessible only within the class.
 default (no modifier): Accessible within the same package.
 protected: Accessible within the same package and by subclasses.
 public: Accessible from any other class.

8. Abstract Class vs. Interface


 Abstract Class: Can have both abstract methods (without body) and
concrete methods (with body). It allows you to define common behavior that
subclasses can inherit.
 Interface: Can only have abstract methods (prior to Java 8). From Java 8
onward, interfaces can also have default and static methods. Interfaces
provide a way to achieve full abstraction and multiple inheritance.

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.

10. Exception Handling: throw, throws, try-catch, and


finally
 try: Block of code that might throw an exception.
 catch: Block of code to handle the exception.
 finally: Block of code that will always execute after try and catch blocks,
regardless of whether an exception occurred.
 throw: Used to explicitly throw an exception.
 throws: Used in method signatures to declare the exceptions that the
method might throw.

11. Serialization, Deserialization, and Externalization


 Serialization: Process of converting an object into a byte stream.
 Deserialization: Process of converting a byte stream back into an object.
 Externalization: Interface that allows control over the serialization process.
 To prevent serialization of attributes, use the transient keyword.

12. Just-In-Time (JIT) Compiler


The JIT compiler improves the performance of Java applications by compiling
bytecode into native machine code at runtime. This makes the execution of
bytecode faster by reducing the interpretation overhead.

13. equals() Method vs. Equality Operator (==)


 equals(): Method to check the equality of two objects based on their state
(content).
 ==: Operator to check if two reference variables refer to the same object in
memory.

14. Garbage Collection in Java: Heap and Stack


Memory
 Heap Memory: Used for dynamic memory allocation of objects and classes.
 Stack Memory: Used for static memory allocation, storing method calls and
local variables.

15. String Constant Pool


A special memory region where Java stores string literals. It helps in saving
memory by reusing instances of identical strings.

16. Can the main method be Overloaded?


Yes, the main method can be overloaded, but the JVM will only call the public
static void main(String[] args) signature as the entry point of the
application.

17. Why is the main method static in Java?


The main method is static so that it can be called without creating an
instance of the class, which is necessary because it serves as the entry point
for the JVM to start execution.

18. The final Keyword


 final class: Cannot be subclassed.
 final method: Cannot be overridden by subclasses.
 final variable: Its value cannot be changed once assigned.

19. final, finally, and finalize Keywords


 final: Used for constants, methods that cannot be overridden, and classes
that cannot be subclassed.
 finally: Block in exception handling that executes regardless of whether an
exception is thrown.
 finalize(): Method called by the garbage collector before an object is
destroyed. It is used for cleanup activities.

20. Using the super Keyword


The super keyword is used to refer to the immediate parent class object. It is
used to access parent class methods and constructors.

21. JVM, JRE, and JDK Differences


 JVM (Java Virtual Machine): Executes Java bytecode.
 JRE (Java Runtime Environment): Provides the libraries and JVM required
to run Java applications.
 JDK (Java Development Kit): Provides tools needed to develop Java
applications, including JRE and development tools.

22. Differences Between Constructor and Method


 Constructor: Initializes a new object. It has the same name as the class and
no return type.
 Method: Performs a specific task. It has its own name and return type.

23. Java: Pass by Value or Pass by Reference?


Java uses pass-by-value. When you pass an object, the reference to the
object is passed by value, meaning the reference itself is copied, not the
actual object.
Diffreence between Fail-Fast and Fail-safe Iterator

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.

3. Why is String immutable in Java?


Immutability of Strings means once you create a string, you cannot
change it. Here’s why:
 Security: If strings were mutable, it would be easy to change the contents of
strings that are being used in security-sensitive operations, like network
connections and file paths.
 Performance: Java stores strings in a pool to save memory. If a string were
mutable, any change to it would affect all references to that string.
 Thread Safety: Immutable objects are naturally thread-safe because their
state cannot change. Multiple threads can use the same string without
synchronization.
 Caching: The hash code of strings is cached when it is created. This makes
operations like lookups in hash tables faster.

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.

4. What is a marker interface?


A marker interface is an interface with no methods or constants. It is used
to "mark" a class in a certain way.

Example: Serializable is a marker interface. When you implement


Serializable, you tell the Java Virtual Machine (JVM) that your class can be
serialized, meaning its state can be converted into a byte stream and saved
to a file or sent over a network.

5. Can you override private and static methods in


Java?
 Private methods: No, you cannot override private methods because they
are not visible to subclasses.
 Static methods: No, you cannot override static methods. However, you can
hide them.

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.

6. What is method hiding?


Method hiding occurs when a subclass defines a static method with the
same name and signature as a static method in the superclass.

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" } }

7. Does finally always execute in Java?


Yes, the finally block always executes, regardless of whether an exception
is thrown or caught, except in a few specific cases like:

 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" ); }

This will print:

php
Copy code
Exception caught Finally block executed

8. What methods does the Object class have?


The Object class has several methods that all classes in Java inherit:

 toString()
 equals(Object obj)
 hashCode()
 clone()
 getClass()
 notify()
 notifyAll()
 wait()
 finalize()
9. How can you make a class immutable?
To make a class immutable:

1. Declare the class as final so it cannot be subclassed.


2. Make all fields private and final so they cannot be modified after the
object is created.
3. Do not provide setters for the fields.
4. Initialize all fields via the constructor.
5. Ensure deep copies of mutable objects are made if necessary, and
returned only via getters.

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; } }

In this example, ImmutablePerson is immutable because once an object of this


class is created, its state cannot be changed.

Difference Between Checked and Unchecked


Exceptions
Checked Exceptions:

 Checked exceptions are exceptions that are checked at compile-time.


 They must be either caught or declared in the method signature using the
throws keyword.
 Examples include IOException, SQLException, etc.
 They are typically recoverable errors and signify conditions that a reasonable
application might want to catch.

Unchecked Exceptions:

 Unchecked exceptions are exceptions that are not checked at compile-time.


 They are subclasses of RuntimeException and do not need to be declared or
caught.
 Examples include NullPointerException, ArrayIndexOutOfBoundsException, etc.
 They usually indicate programming bugs, such as logic errors or improper
use of an API.

What Happens Behind the Code int data = 50 / 0;?

 This line of code will cause a ArithmeticException at runtime.


 Specifically, it will throw a java.lang.ArithmeticException with the message
"by zero".
 This is an unchecked exception, so it does not need to be caught or declared,
but if uncaught, it will terminate the program.

Why Use Multiple Catch Blocks?


 Multiple catch blocks are used to handle different types of exceptions that
may be thrown by a block of code.
 Each catch block can handle a specific exception type, allowing for more
precise and meaningful error handling.
 This approach helps in maintaining the program's robustness by providing
tailored responses to different failure modes.

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 }

Is There Any Possibility When the Finally Block is Not


Executed?
 Generally, the finally block is always executed after the try and catch
blocks, regardless of whether an exception is thrown or not.
 However, there are a few scenarios where the finally block might not
execute:
1. If the JVM exits while the try or catch block is being executed (e.g.,
System.exit()).
2. If the thread executing the try-catch-finally block is interrupted or killed.
3. If there is an exception thrown in the finally block itself that is not caught.

What is Exception Propagation?


 Exception propagation refers to the process by which an exception is passed
up the call stack until it is caught by an appropriate exception handler.
 If a method does not catch an exception, the exception is propagated to the
caller of the method. This continues until the exception is caught or the
program terminates.
 Example:

java

Copy code

public void method1() throws IOException { method2(); } public void method2() throws
IOException { // code that may throw IOException }

Difference Between the throw and throws Keyword

 throw keyword:

 Used to explicitly throw an exception.


 It is typically used within a method.
 Example:
java
Copy code
throw new IllegalArgumentException ( "Invalid argument" );

 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 }

Four Rules for Using Exception Handling with Method


Overriding

1. Same Exception:
 If the superclass method declares an exception, the overridden method in
the subclass can declare the same exception.
java

Copy code

class SuperClass { void method() throws IOException { // code } } class SubClass


extends SuperClass { void method() throws IOException { // code } }

2. Subclass Exception:

 If the superclass method declares an exception, the overridden method can


declare a subclass of that exception.
java

Copy code

class SuperClass { void method() throws IOException { // code } } class SubClass


extends SuperClass { void method() throws FileNotFoundException { // code } }

3. No Exception:

 If the superclass method declares an exception, the overridden method can


declare no exception.
java

Copy code

class SuperClass { void method() throws IOException { // code } } class SubClass


extends SuperClass { void method() { // code } }

4. Unchecked Exceptions:

 If the superclass method does not declare an exception, the overridden


method cannot declare a checked exception. However, it can declare an
unchecked exception (runtime exception).
java

Copy code

class SuperClass { void method() { // code } } class SubClass extends SuperClass {


void method() throws RuntimeException { // code } }
Explain what is JDBC?

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);

3. Can you get a null ResultSet?

No, you can never get null Resultset(). The ResultSet.next() can return null only if the
next record does not comprise a row.

4. Explain the difference between ResultSet Vs. RowSet vs in JDBC?

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.

5. What is a JDBC driver?


A JDBC driver is a software component having multiple interfaces and classes that
enables a Java application to communicate with a database. To establish a link with
individual databases, JDBC needs specific drivers for each database. These drivers are
available with the database vendor along with 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.

6. What is DriverManager in JDBC?

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.

7. Explain the different drivers of JDBC.

There are four different drivers in JDBC. They are:

 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?

The DatabaseMetaData is an interface that provides methods to gain information about


the database. This interface helps in obtaining database-related information, such as
database name, driver name, database version, the total number of tables or views, and
so on.

11. Explain the differences between JDBC and ODBC?

ODBC (Open Database


JDBC (Java Database Connectivity)
Connectivity)

ODBC can be used for things


JDBC is used for the Java language. such as C, C++, Java, and so
on.

ODBC can be used only for the


JDBC can be used on any platform; thus,
Windows platform; thus, making
making it platform-independent.
it platform-dependent.

JDBC drivers are developed using the Java Most of the ODBC Drivers have
language. been developed using native
languages such as C, C++

ODBC is not recommended for


JDBC is ideal for Java applications as there are Java applications as its
no performance issues. performance is not great due to
internal conversion.

JDBC is Object Oriented. ODBC is procedural.

12. What is Rowset?

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.

13. What is ResultSet?

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.

14. What are the types of ResultSet?

There are three types of ResultSet:

 TYPE_FORWARD_ONLY: The cursor only moves forward.

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

15. Explain the advantages of a Rowset.

The advantages of using RowSet are:

 It is flexible and easier to use.

 It is Updatable and Scrollable by default.

16. Explain what are the different JDBC statements:

Following are the three types of JDBC statements:

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

 Callable Statement: Executes stored procedures.

17. Are there any advantages of using a Prepared Statement in Java?

A Prepared Statement executes certain SQL statements repetitively. This statement is


compiled only once even though it is executed “n” number of times.

18. Explain the term connection pooling.

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.

19. Explain the types of JDBC Architecture?

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.

 Three-tier Architecture: This model is the complete opposite of two-tier architecture. An


application server is used as a mediator between the Java program or JDBC driver and the
database. The Java program sends a request to the application server. The server then
forwards this request to the database and waits for a response from the database.

20. What are the main components of JDBC?

Following are the four major components available in JDBC:

 JDBC Driver Manager

 JDBC API

 JDBC Test Suite

 JDBC-ODBC Bridge

21. What are the steps to connect with JDBC?

Following are the 6 basic steps to connect with the database in Java.

1. Import the JDBC packages.

2. Load and register the JDBC driver.

3. Open and establish a connection to the database.

4. Creation a statement object to perform a query.

5. Execute the statement object and return a query ResultSet(). Then process the ResultSet().

6. Close the ResultSet() and statement objects.

7. Close the connection.

22. Explain the meaning of hot backup and cold backup.

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.

23. What are the steps to connect with JDBC?

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.

24. Explain if the JDBC-ODBC Bridge supports different concurrent open


statements per connection?

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.

26. Explain the difference between executeQuery, executing, and


executeUpdate in JDBC?

 executeQuery(): The executeQuery() can be used for select query.

 execute(): The execute() can be used for any type of SQL Query.

 executeUpdate(): The executeUpdate() can be used to modify/update tables.

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?

The setAutoCommit(false) is used to turn off the Auto Commit.

29. Explain the role of Class.forName while loading drivers in brief?

The Class.forName generates an instance of JDBC driver and a register with


DriverManager.

Become a Software Development Professional


Full Stack Java Developer


 Kickstart Full Stack Java Developer career with industry-aligned curriculum by experts
 Hands-on practice through 20+ projects, assessments, and tests

6 months

View Program

Full Stack Web Developer - MEAN Stack


 Comprehensive Blended Learning program
 8X higher interaction in live online classes conducted by industry experts

11 months

View Program

Not sure what you’re looking for?View all Related Programs

30. Why are prepared statements faster?

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.

31. What are the JDBC API components?

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.

 PrepareStatement: The prepareStatement() method of connection class, the


prepareStatement object is created.

 DatabaseMetaData: The Connection interface's getMetaData() method returns an object of


DatabaseMetaData.

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

 Clob: Character Large Object is referred to as Clob. Different database management


systems utilize it as a data type to store character files.

 SQLException: It is an exception class that offers details on problematic database access.

32. What are the JDBC statements?

Statements are used in JDBC to communicate SQL commands to databases and


receive data from them. Three categories of statements exist:

 Statements

 Prepared Statements

 Collable Statement

33. Mention the return type of Class.forName() method?

The object of java.lang.Class Object is the return type of the Class.forName() method.

34. Explain the differences between Statement and PreparedStatement


interface?
Statement Prepared statement

The Statement interface provides strategies for


the database to run queries. The statement It is a subinterface of a
interface serves as a factory for ResultSet, Statement. It is used for
offering the factory function to obtain a ResultSet parameterized query execution.
object.

The query is only compiled once


When using Statement, the query is compiled
in the case of
each time when the application is executed.
PreparedStatement.

We use prepared statements


The Statement is mostly employed when a static when the requirement for input
query has to be executed at runtime. parameters occurs at the
runtime query.

35. How can we set a null value in JDBC PreparedStatement?

We can set a null value to an index using the setNull()method. Below given is the
syntax for the given method:

void setNull(int parameterIndex, int sqlType) throws SQLException

36. Explain the benefits of Prepared Statement over Statement?

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

37. Explain the execution of stored procedures using Callable Statement?

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.

Make a network connection.

Make the Callable Statement Object.

Give the values, then run the query.

The values can be located in the database, so check there.

38. Describe the role of the JDBC DriverManager class.

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.

39. Mention the functions of the JDBC Connection interface?

The database session is maintained by the Connection interface. The management of


transactions is possible with it. To return the instance of statement, Prepared
Statement, Callable Statement, and DatabaseMetaData, the factory method is provided
by the JDBC connection interface.

40. What is the JDBC ResultSet interface?


A table row is represented by the ResultSet object. It can be used to retrieve data from
the database and move the cursor pointer. The ResultSet object can only move forward
by default and cannot be updated.

41. What is the JDBC ResultSetMetaData interface?

The table's information, including the total number of columns, column names, column
types, etc., is returned via the ResultSetMetaData interface.

42. Mention the interface which enables transaction management in JDBC.

The Connection interface offers transaction management methods like commit(),


rollback(), and others.

43. Explain batch processing and method to perform batch processing in


JDBC?

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.

Load the driver class

Create Connection

Create Statement

Add query in the batch

Execute the Batch

Close Connection

44. Explain CLOB and BLOB data types in JDBC?

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

CLOB: A CLOB is a character-large object of variable length that is used to store


character-based data, such as files in various databases. On an Oracle Database, it can
hold 128 GB, while a MySQL database can handle up to 2 GB. Considered to be a
character string is a CLOB.

45. What are the different types of lockings in JDBC?

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.

 Table locks: The table is protected by table locks.

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

47. How can we store the file in the Oracle database?

CLOB datatype is used in the table to store files in the Oracle database.

48. How can we retrieve the file in the Oracle database?

To retrieve the file in the Oracle database we use the getClob() method of the prepared
statement.

49. Mention the differences between stored procedures and functions?

Stored procedures Functions


Performs business logic Performs the calculation

Will not have the return type Will have the return type.

Should return 0 or more values Should return only one value

It supports both input and output parameters It supports only one parameter.

Become a Software Development Professional


Full Stack Java Developer


 Kickstart Full Stack Java Developer career with industry-aligned curriculum by experts
 Hands-on practice through 20+ projects, assessments, and tests

6 months

View Program

Full Stack Web Developer - MEAN Stack


 Comprehensive Blended Learning program
 8X higher interaction in live online classes conducted by industry experts

11 months

View Program

Not sure what you’re looking for?View all Related Programs

50. Mention ways to maintain the integrity of a database by using JDBC?


We must ensure the ACID properties to maintain the integrity of a database. Atomicity,
consistency, isolation, and durability are referred to as ACID properties.

51. What is the role of the JDBC setMaxRows method?

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.

53 What is serilization in java ?

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.

Key Points About Serialization in Java:

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();

3. Deserialization Process: The reverse process, deserialization, is handled by the


ObjectInputStream class, which has methods like readObject() to reconstruct the
object from the byte stream.

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;

6. Custom Serialization: By overriding the writeObject and readObject methods, you


can customize the serialization and deserialization processes.

java
Copy code
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
// custom serialization code
}

private void readObject(ObjectInputStream in) throws IOException,


ClassNotFoundException {
in.defaultReadObject();
// custom deserialization code
}

Advantages of Serialization:

 Persistence: Objects can be saved to files and retrieved later.


 Communication: Objects can be sent over networks (e.g., for remote method
invocation).
 Caching: Objects can be cached for performance improvements.

Considerations and Limitations:

 Performance: Serialization can introduce performance overhead.


 Versioning: Changes in class structure can lead to incompatibility issues unless handled
carefully.
 Security: Serialized data can be tampered with, leading to security vulnerabilities.

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 ?

Steps to Make a Class Serializable

1. Implement the Serializable Interface: This interface is a marker interface, which


means it does not contain any methods. Its purpose is to signal to the Java runtime that
instances of this class can be serialized.

java
Copy code
import java.io.Serializable;

public class MyClass implements Serializable {


// class fields and methods
}

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;

Example of a Serializable Class

Here is a complete example:

java
Copy code
import java.io.Serializable;

public class Employee implements Serializable {


private static final long serialVersionUID = 1L;

private String name;


private int age;
private transient double salary; // This field will not be serialized

public Employee(String name, int age, double salary) {


this.name = name;
this.age = age;
this.salary = salary;
}

// Getters and setters

@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;

public class Employee implements Serializable {


private static final long serialVersionUID = 1L;

private String name;


private int age;
private transient double salary;

public Employee(String name, int age, double salary) {


this.name = name;
this.age = age;
this.salary = salary;
}

// Custom serialization logic


private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeDouble(salary);
}

// Custom deserialization logic


private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
salary = in.readDouble();
}

@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}

In this custom implementation:

 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.*;

public class SerializationDemo {


public static void main(String[] args) {
Employee emp = new Employee("John Doe", 30, 50000.0);

// Serialize the object


try (ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("employee.ser"))) {
out.writeObject(emp);
} catch (IOException e) {
e.printStackTrace();
}

// Deserialize the object


try (ObjectInputStream in = new ObjectInputStream(new
FileInputStream("employee.ser"))) {
Employee deserializedEmp = (Employee) in.readObject();
System.out.println("Deserialized Employee: " + deserializedEmp);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

What is the difference between Serializable and Externalizable interface in Java?


The Serializable and Externalizable interfaces in Java are both used for object
serialization, but they have significant differences in how they work and the control they provide
over the serialization process.

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
}

private void readObject(ObjectInputStream in) throws IOException,


ClassNotFoundException {
in.defaultReadObject();
// Custom deserialization 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

1. Explicit Control: Externalizable extends Serializable and adds two methods:


writeExternal and readExternal. These methods must be implemented by the class
and provide explicit control over the serialization and deserialization processes.

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();
}
}

2. No Default Behavior: Unlike Serializable, Externalizable does not have default


serialization behavior. The entire process is manual, meaning you must explicitly define
how each field is serialized and deserialized.
3. Efficiency: Because you have complete control over the serialization process, using
Externalizable can be more efficient than Serializable. You can choose to serialize
only the necessary fields and optimize the format, reducing the size and improving
performance.
4. No Support for transient Keyword: In Externalizable, you are responsible for
handling all fields, including those you might want to exclude from serialization. The
transient keyword does not have the same effect as in Serializable.

Comparison Summary

Feature Serializable Externalizable


Type Marker Interface Interface with methods
Methods None writeExternal, readExternal
Default Serialization Yes, handled by Java No, must be manually implemented
Via writeObject, readObject Directly in writeExternal,
Custom Serialization
methods readExternal
Control Limited, via customization Full control over the process
Less efficient (due to default
Efficiency More efficient (full control)
behavior)
transient Keyword
Yes No
Support

When to Use Which

 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

What is a serialVersionUID, and why should I use it?


It is a version number that is assigned to each serializable class. A serializable class
creates a field called serialVersionUID. To declare its own serialVersionUID.The field
must be :
1. Static.
2. Final.
3. Long data type.

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.

What is the need for Serialization?


It is used when we need to send data need over a network or store it in files. By data, we mean
objects rather than text. The issue now is that your network framework and hard disc are
hardware components and accept bits and bytes but not Java objects.

Why are static member variables not serialized?


Static variables are defined as variables that belong to a class rather than an object. They retain
their value even when they are out of their scope. Now, serialization is converting and storing an
object's state because static variables belong to the class rather than the object. Thus they are
not serialized.

What is a transient variable? What is the purpose of it?


Ans. Transient variables are not saved during the Serialization process. As the name
implies, they do not constitute part of the object's state. We can use this variable to
prevent certain fields from being serialized. For instance, a field that is not serializable
should be marked transient or static

How can we implement Serialization in java?


Ans. The most common way of implementation is the Serialization Interfaces in Java. If
an object implements this interface, it can be transferred as a byte stream over the
network. Another option is to use the Externalizable interface.

You might also like