0% found this document useful (0 votes)
3 views7 pages

Java Important Questions Answers

Uploaded by

sunil19211491200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Java Important Questions Answers

Uploaded by

sunil19211491200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

JDBC

# 1. What is JDBC?
1. JDBC (Java Database Connectivity) is an API provided by Java for
connecting and interacting with databases. It allows Java applications to
send SQL queries to databases and retrieve results. JDBC acts as a bridge
between the Java application and a database.
2. JDBC supports both relational and non-relational databases. It
provides classes and interfaces for establishing a connection, executing
queries, and handling results.
3. JDBC is platform-independent and works with any database that supports
the JDBC driver. It simplifies database programming by abstracting the
underlying complexities of database communication.
4. Common JDBC interfaces include Connection, Statement,
PreparedStatement, CallableStatement, and ResultSet. These components are
essential for performing database operations.

# 2. What is the role of DriverManager in JDBC?


1. DriverManager is a class in JDBC responsible for managing database
drivers. It provides a mechanism to establish a connection between the
Java application and a database.
2. It uses the registered drivers to connect to the database based on the
connection URL provided. DriverManager ensures that the correct driver is
loaded for the specified database.
3. The `getConnection()` method in DriverManager is used to create a
database connection. It takes the database URL, username, and password as
parameters.
4. DriverManager also provides methods for logging and tracing driver
activity. This helps in debugging and monitoring database interactions.

# 3. Explain the purpose of the ResultSet interface in JDBC.


1. ResultSet represents a table of data retrieved from a database after
executing a SQL query. It provides methods to navigate through the rows
and access column values.
2. The ResultSet cursor is initially positioned before the first row and
can be moved using methods like `next()`, `previous()`, `first()`, and
`last()`.
3. ResultSet supports retrieving data in various formats using methods
like `getString()`, `getInt()`, `getDouble()`, etc. It also provides
metadata about the result set.
4. ResultSet can be scrollable or updatable, depending on the Statement
used to create it. This flexibility allows developers to handle complex
data interactions.

# 4. What are the different types of JDBC drivers?


1. Type-1: JDBC-ODBC Bridge Driver - This driver acts as a bridge between
JDBC and ODBC drivers. It is platform-dependent and less efficient.
2. Type-2: Native-API Driver - It converts JDBC calls to database-
specific native API calls. It requires native libraries and is faster
than Type-1.
3. Type-3: Network Protocol Driver - It uses a middleware server to
convert JDBC calls into database-specific protocol calls. This driver is
suitable for enterprise applications.
4. Type-4: Thin Driver - It directly converts JDBC calls into database
protocol calls. It is platform-independent, highly efficient, and widely
used.

# 5. What is the significance of the Statement object in JDBC?


1. The Statement object is used to execute SQL queries against a
database. It supports executing static SQL queries that do not require
input parameters.
2. It provides three main methods: `executeQuery()` for SELECT queries,
`executeUpdate()` for INSERT, UPDATE, DELETE, and `execute()` for any SQL
command.
3. The Statement object retrieves query results into a ResultSet, which
can be processed further. It allows developers to interact with database
data dynamically.
4. Although simple, Statement is less efficient than PreparedStatement
for executing parameterized queries due to lack of pre-compilation.

# 6. What is the Runnable interface and PreparedStatement?


1. Runnable is an interface in Java used to define a task for a thread.
It contains a single method `run()` that must be implemented to specify
the thread's task.
2. Runnable provides a way to achieve multithreading without inheriting
the Thread class, allowing a class to extend other classes.
3. PreparedStatement is a subclass of Statement used for executing
parameterized queries. It pre-compiles SQL queries, making them faster
and preventing SQL injection attacks.
4. PreparedStatement uses placeholders (e.g., `?`) for parameters, which
can be set using methods like `setString()` and `setInt()`. This enhances
query security and reusability.

# 7. Explain the JDBC architecture with all the components involved.


1. JDBC architecture consists of two layers: the JDBC API and the JDBC
Driver. The API provides interfaces for applications, while drivers
handle communication with databases.
2. The core components include DriverManager, Connection, Statement,
PreparedStatement, CallableStatement, and ResultSet. These work together
to manage database interactions.
3. The architecture supports various drivers (Type-1 to Type-4) to
connect Java applications to different databases. It ensures platform
independence and database interoperability.
4. The process involves loading the driver, establishing a connection,
executing SQL queries, processing results, and closing resources.

# 8. What is the ResultSet interface? Discuss the different types of


ResultSet and their methods.
1. ResultSet is an interface representing the result of a SQL query. It
provides methods to iterate through rows and access data.
2. ResultSet types include TYPE_FORWARD_ONLY (default, moves only
forward), TYPE_SCROLL_INSENSITIVE (scrollable but not updated
dynamically), and TYPE_SCROLL_SENSITIVE (scrollable and dynamically
updated).
3. Common methods include `next()`, `previous()`, `getString()`,
`getInt()`, `getDouble()`, and `close()`. These allow flexible data
access and manipulation.
4. ResultSet also supports updating data directly when created as
updatable, enabling advanced database operations.

# 9. Explain the process of executing SQL queries using Statement,


PreparedStatement, and CallableStatement.
1. Statement is used for executing simple, static SQL queries without
parameters. It is created using the `createStatement()` method and
executes queries with methods like `executeQuery()`.
2. PreparedStatement is used for executing parameterized queries. It is
created using `prepareStatement()` and provides methods to set parameters
securely.
3. CallableStatement is used for executing stored procedures. It supports
input, output, and inout parameters using methods like
`registerOutParameter()`.
4. Each method provides a way to process results, close resources, and
ensure efficient database interaction based on query requirements.

# 10. Java program using PreparedStatement to update salary:


```java
import java.sql.*;

public class UpdateEmployeeSalary {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection con = DriverManager.getConnection(url, user,


password)) {
String query = "UPDATE Employee SET salary = ? WHERE ID = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setDouble(1, 75000);
ps.setInt(2, 101);

int rowsUpdated = ps.executeUpdate();


System.out.println(rowsUpdated + " row(s) updated.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```

# 11. Java program to delete salary column from Emp table:


```java
import java.sql.*;

public class DeleteColumn {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";
try (Connection con = DriverManager.getConnection(url, user,
password)) {
String query = "ALTER TABLE Emp DROP COLUMN salary";
Statement stmt = con.createStatement();

stmt.executeUpdate(query);
System.out.println("Column 'salary' deleted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```

Multithreading

# 1. What is multithreading?
1. Multithreading is a programming concept where multiple threads run
concurrently within a process. Threads share the same memory space,
making inter-thread communication efficient.
2. It helps in performing multiple tasks simultaneously, improving
application performance and resource utilization.
3. Threads can be created using the Thread class or Runnable interface in
Java. Each thread runs independently, enabling multitasking.
4. Multithreading is widely used in applications requiring parallelism,
such as gaming, simulations, and server management.

# 2. Difference between Thread class and Runnable interface:


1. The Thread class provides a direct way to create and start a thread by
extending it. Runnable is an interface implemented to define a task for a
thread.
2. Using the Runnable interface allows a class to inherit other classes,
while extending Thread restricts inheritance.
3. Threads created using Runnable are executed by passing a Runnable
object to a Thread constructor. This promotes better design and
separation of concerns.
4. Both approaches support multithreading but using Runnable is preferred
in scenarios requiring flexibility and extensibility.

# 3. What are the various states in the lifecycle of a thread?


1. A thread's lifecycle includes several states: NEW, RUNNABLE, BLOCKED,
WAITING, TIMED_WAITING, and TERMINATED.
2. In the NEW state, a thread is created but not started. When `start()`
is called, it moves to the RUNNABLE state, ready to run when the CPU
allows.
3. BLOCKED occurs when a thread is waiting for a monitor lock, while
WAITING and TIMED_WAITING occur during inter-thread communication.
4. TERMINATED indicates that a thread has completed execution. The
lifecycle is managed by the JVM.

# 4. What is thread priority in Java? How to set thread priorities?


1. Thread priority determines the order in which threads are scheduled
for execution. It ranges from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with
5 (NORM_PRIORITY) as default.
2. Priorities are hints to the thread scheduler but do not guarantee
execution order. Higher-priority threads are more likely to execute
first.
3. Thread priority can be set using the `setPriority()` method. For
example, `thread.setPriority(Thread.MAX_PRIORITY)` sets a thread's
priority to the highest.
4. Proper use of thread priorities helps optimize performance in
applications with critical tasks.

# 5. What is synchronization in Java?


1. Synchronization is a mechanism to control thread access to shared
resources. It prevents data inconsistency and thread interference.
2. Synchronized blocks or methods lock the resource so only one thread
can access it at a time. This ensures thread-safe operations.
3. Synchronization is achieved using the `synchronized` keyword. For
example, `synchronized void method()` locks the method for one thread at
a time.
4. Excessive synchronization can lead to performance issues like thread
contention and deadlocks, so it should be used judiciously.

# 6. What is wait(), notify(), and notifyAll() in multithreading?


1. `wait()`, `notify()`, and `notifyAll()` are methods used in inter-
thread communication. They allow threads to coordinate their actions.
2. `wait()` causes a thread to release its lock and enter a waiting state
until another thread calls `notify()` or `notifyAll()`.
3. `notify()` wakes up a single waiting thread, while `notifyAll()` wakes
up all waiting threads. These methods must be called within a
synchronized context.
4. Proper use of these methods ensures smooth communication between
threads, avoiding issues like thread starvation.

# 7. What is the method to set thread priority?


1. The `setPriority()` method in the Thread class is used to set a
thread's priority. It takes an integer value from 1 to 10.
2. For example, `thread.setPriority(Thread.MAX_PRIORITY)` sets the thread
to the highest priority (10).
3. Higher-priority threads are more likely to execute earlier but are not
guaranteed by the JVM.
4. Thread priorities should be used carefully to avoid affecting
application fairness and performance.

# 8. Java program to print "Hello Java" message 10 times:


```java
public class HelloJava {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Hello Java");
}
}
}
```

# 9. Java program that creates and starts two threads using the Thread
class:
```java
public class TwoThreads {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread 1: " + i);
}
});

Thread t2 = new Thread(() -> {


for (int i = 1; i <= 10; i++) {
System.out.println("Thread 2: " + i);
}
});

t1.start();
t2.start();
}
}
```

# 10. Explain the lifecycle of a thread with a diagram:


1. The lifecycle includes the following states: NEW, RUNNABLE, BLOCKED,
WAITING, TIMED_WAITING, and TERMINATED.
2. NEW: Thread is created but not started. RUNNABLE: Thread is ready to
run but waiting for CPU time.
3. BLOCKED: Waiting to acquire a lock. WAITING/TIMED_WAITING: Waiting
indefinitely or for a specified time.
4. TERMINATED: Thread has finished execution. The diagram visually
represents transitions between these states.

# 11. How can a thread be created using the Thread class and Runnable
interface?
1. Using Thread Class: Extend the Thread class and override the `run()`
method. Create an instance and call `start()` to begin execution.
2. Using Runnable Interface: Implement the Runnable interface, define the
`run()` method, and pass the instance to a Thread constructor.
3. Example using Thread:
```java
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
MyThread t = new MyThread();
t.start();
```
4. Example using Runnable:
```java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable running");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
```

# 12. Discuss the thread synchronization mechanism in Java.


1. Synchronization controls access to shared resources, preventing thread
interference and ensuring data consistency.
2. Synchronized methods or blocks use intrinsic locks to allow only one
thread at a time to execute the critical section.
3. Example:
```java
synchronized void method() {
// Critical section
}
```
4. Synchronization prevents race conditions but can lead to issues like
deadlocks if not used carefully. It ensures thread-safe operations in
concurrent environments.

You might also like