Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Advance Java Answers

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

2 MARKS QUESTIONS

1. JDBC stands for Java Database Connectivity. It is a Java API that allows Java programs to interact
with databases. JDBC enables developers to write database applications in Java without having to
deal with the low-level details of database connectivity.

Components of JDBC:

- DriverManager: Manages a list of database drivers. It can be used to establish a connection to the
database.

- Driver: Provides the implementation for the JDBC API. Different database vendors provide their own
JDBC drivers.

- Connection: Represents a connection to the database. It can be used to create Statement,


PreparedStatement, and CallableStatement objects.

- Statement: Used to execute SQL queries and statements against the database.

- ResultSet: Represents the result set of a SQL query. It allows the retrieval and manipulation of data
returned by a SELECT statement.

- SQLException: Handles exceptions that occur during database interactions.

2. Types of drivers:

- Type 1: JDBC-ODBC Bridge Driver

- Type 2: Native-API Driver

- Type 3: Network Protocol Driver

- Type 4: Thin Driver (Native Protocol Pure Java Driver)

3. Advantages of native protocol pure Java drivers:

- Platform independence: These drivers are written purely in Java and do not rely on native code,
making them platform-independent.

- Performance: Since they directly communicate with the database server, they can offer better
performance compared to other drivers.

- Security: They can be more secure as they do not rely on external libraries or components.

- No client-side configuration: They do not require additional client-side configuration as they are
self-contained within the Java application.

4. Disadvantages of JDBC-native API driver:


- Platform dependency: These drivers rely on native libraries and code, making them platform-
dependent.

- Performance: They might not offer the same level of performance as native protocol pure Java
drivers.

- Installation and configuration: They require additional setup and configuration on the client-side.

- Limited to specific databases: Each native API driver is typically designed for a specific database
vendor, limiting their usability across different databases.

5. JDBC statements objects:

- Statement

- PreparedStatement

- CallableStatement

6. Purpose of `createStatement()` and `executeQuery()` methods:

- `createStatement()`: This method is used to create a Statement object for sending SQL statements
to the database.

- `executeQuery()`: This method is used to execute a SQL SELECT statement and return the ResultSet
object representing the result set of the query.

7. `TYPE_SCROLL_SENSITIVE` in ResultSet of JDBC:

- `TYPE_SCROLL_SENSITIVE` is a constant that indicates that the ResultSet object is scrollable and
sensitive to changes made by others to the database. This means that if another process modifies
the data in the database, those changes will be reflected in the ResultSet.

8. Metadata:

Metadata refers to data that describes other data. In the context of databases and JDBC, metadata
provides information about the structure and properties of database objects such as tables, columns,
and constraints.

Types of metadata in JDBC:

- Database metadata: Provides information about the database as a whole, such as its name, version,
and supported features.

- Result set metadata: Provides information about the structure of the result set returned by a query,
such as column names, types, and sizes.
- Parameter metadata: Provides information about the parameters of a PreparedStatement object,
such as parameter types and modes.

9. Methods of ResultSetMetaData:

Two methods of ResultSetMetaData are:

- `getColumnCount()`: Returns the number of columns in the ResultSet.

- `getColumnLabel(int column)`: Returns the label for the specified column, if a label is specified for
the column in the SQL query; otherwise, it returns the column name.

10. Multithreading:

Multithreading is a programming concept that allows multiple threads of execution to run


concurrently within a single process. Each thread represents a separate flow of control, allowing
tasks to be performed simultaneously.

Thread process involves:

- Creation: Threads are created using either extending the Thread class or implementing the
Runnable interface.

- Starting: Threads are started using the `start()` method.

- Running: Threads execute their code concurrently.

- Sleeping or waiting: Threads can be made to sleep or wait for a specified period of time.

- Termination: Threads terminate either by completing their tasks or by being explicitly stopped.

11. Methods to create a thread:

Threads can be created in Java by:

- Extending the `Thread` class and overriding its `run()` method.

- Implementing the `Runnable` interface and providing the implementation for the `run()` method.

12. Main thread:

The main thread is the thread from which a Java program starts its execution. It is created
automatically when a Java program begins execution and serves as the entry point for the program.
All other threads in the program are spawned from the main thread or from threads created by it.

13. Sockets and port numbers:


- Socket: A socket is an endpoint for communication between two machines over a network. It
enables bidirectional data transfer between client and server applications.

- Port numbers: Port numbers are used to uniquely identify different communication endpoints
within a single host. They range from 0 to 65535, with well-known ports (0-1023) reserved for
specific services and applications.

14. Proxy server:

A proxy server is an intermediary server between a client and the internet. It acts as a gateway,
forwarding requests from clients to other servers and caching responses to improve performance
and security. The purpose of a proxy server includes caching frequently accessed resources,
controlling access to the internet, and enhancing privacy by hiding the client's IP address.

15. Socket and ServerSocket class:

- Socket class: Represents a client-side endpoint for communication over a network. It can establish a
connection to a server and send and receive data.

- ServerSocket class: Represents a server-side endpoint that listens for incoming connections from
clients. It can accept incoming connections and create Socket objects to handle communication with
clients.

16. URL format in networking:

The format of a URL (Uniform Resource Locator) in networking typically consists of the following
components:

```

protocol://hostname:port/path?query

```

- Protocol: Specifies the communication protocol to be used, such as HTTP, FTP, or JDBC.

- Hostname: Specifies the domain name or IP address of the server.

- Port: Specifies the port number on the server where the service is running.

- Path: Specifies the path to the resource on the server.

- Query: Specifies parameters or data to be passed to the server.

17. Difference between TCP/IP and UDP:

- TCP/IP (Transmission Control Protocol/Internet Protocol) is a connection-oriented protocol that


provides reliable, ordered, and error-checked delivery of data packets. It establishes a connection
between sender and receiver before data transfer.
- UDP (User Datagram Protocol) is a connectionless protocol that provides unreliable, unordered, and
connectionless delivery of data packets. It does not establish a connection before sending data and
does not guarantee delivery.

18. Use of DatagramSocket class:

The DatagramSocket class in Java is used to implement networking applications based on the UDP
protocol. It represents a socket for sending and receiving datagram packets, which are individual
units of data transmitted over a network.

19. Methods to provide information about a socket:

Two methods to provide information about a socket:

- `getInetAddress()`: Returns the InetAddress object representing the IP address of the remote
endpoint of the socket.

- `getPort()`: Returns the port number of the remote endpoint of the socket.

20. Package containing classes and interfaces of networking:

The `java.net` package contains

classes and interfaces for networking in Java. It provides support for networking operations such as
socket programming, URL handling, and protocol implementation.

4 MARKS QUESTIONS

1. **JDBC-ODBC Bridge Driver:**

The JDBC-ODBC bridge driver is a type 1 JDBC driver that enables Java applications to interact with
databases using ODBC (Open Database Connectivity) drivers. It acts as a mediator between Java
applications and ODBC-compliant databases, allowing Java programs to access data stored in
databases via SQL queries.

2. **JDBC Net Pure Java Driver:**

The JDBC Net Pure Java driver, also known as the type 4 driver, is a JDBC driver that communicates
directly with the database server using a database-specific protocol. Unlike the JDBC-ODBC bridge
driver, it does not rely on ODBC, making it purely Java-based and platform-independent. This driver is
faster and more efficient compared to the JDBC-ODBC bridge driver.
3. **Advantages and Disadvantages of Multithreading:**

Advantages:

- Increased responsiveness and interactivity in applications.

- Enhanced resource utilization, as multiple tasks can execute concurrently.

- Simplified program design by breaking complex tasks into smaller, manageable threads.

Disadvantages:

- Complexity in programming and debugging due to concurrency issues like race conditions and
deadlocks.

- Increased resource consumption and potential for resource contention.

- Difficulty in reasoning about thread interactions and ensuring thread safety.

4. **JDBC Process:**

The JDBC (Java Database Connectivity) process involves the following steps:

- Loading the JDBC driver: Load the appropriate JDBC driver using `Class.forName()` method.

- Establishing a connection: Create a connection to the database using


`DriverManager.getConnection()` method.

- Creating a statement: Create a statement object for executing SQL queries against the database.

- Executing queries: Execute SQL queries using the statement object (`Statement` or
`PreparedStatement`).

- Handling results: Process the results obtained from the database (if any).

- Closing resources: Close the connection and other JDBC resources to release database and system
resources.

5. **PreparedStatement():**

`PreparedStatement` is a feature in JDBC that allows precompilation of SQL statements. It


represents a precompiled SQL statement that can be executed multiple times with different
parameters. This improves performance and security by preventing SQL injection attacks.

Example:

```java

String query = "INSERT INTO employees (id, name, age) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);

pstmt.setInt(1, 101); // Set parameter 1 to 101

pstmt.setString(2, "John Doe"); // Set parameter 2 to "John Doe"

pstmt.setInt(3, 30); // Set parameter 3 to 30

pstmt.executeUpdate(); // Execute the prepared statement

```

6. **CallableStatement:**

`CallableStatement` is a type of JDBC statement used to call stored procedures in the database. It
extends `PreparedStatement` and provides methods to execute stored procedures with input and
output parameters.

7. **Advantages and Disadvantages of Multithreading:**

Please note that this question is repeated. Refer to the answer given in question 3.

8. **Life Cycle of Multithreading:**

The life cycle of a thread in Java includes the following states:

- New: The thread is in the new state if it has been created but not yet started.

- Runnable: The thread is in the runnable state if it's eligible to run but the scheduler has not
selected it to be the running thread.

- Running: The thread is in the running state if it's currently executing its code.

- Blocked: The thread is in the blocked state if it's waiting for a monitor lock to enter a synchronized
block/method.

- Waiting: The thread is in the waiting state if it's waiting indefinitely for another thread to perform
a particular action.

- Terminated: The thread is in the terminated state if it has exited its run method and has stopped.

9. **Thread Priorities:**

Thread priorities in Java range from 1 to 10, where 1 is the lowest priority and 10 is the highest.
Thread priorities are used by the thread scheduler to determine the order in which threads are
executed. Higher-priority threads are given preference over lower-priority threads.

Example:
```java

Thread t1 = new Thread();

t1.setPriority(Thread.MAX_PRIORITY); // Set highest priority

Thread t2 = new Thread();

t2.setPriority(Thread.MIN_PRIORITY); // Set lowest priority

```

10. **Synchronization in Multithreading:**

Synchronization in multithreading is the process of controlling access to shared resources or critical


sections of code by allowing only one thread to execute them at a time. It prevents race conditions
and maintains data consistency.

11. **Inter-thread Communication:**

Inter-thread communication refers to the mechanism by which threads exchange information or


coordinate their actions in a multithreaded program. It is typically achieved using methods such as
`wait()`, `notify()`, and `notifyAll()` provided by the `Object` class.

12. **Listening for UDP Packets and Sending UDP Packets:**

Listening for UDP packets involves creating a `DatagramSocket` and using it to receive incoming
UDP packets. Sending UDP packets involves creating a `DatagramSocket`, constructing a
`DatagramPacket` containing the data to be sent, and then sending it using the `send()` method of
`DatagramSocket`.

13. **Client-Server Model:**

The client-server model is a distributed computing architecture where client devices (e.g.,
computers, smartphones) request services or resources from server devices (e.g., servers, databases)
over a network. Clients initiate requests, and servers respond to these requests by providing services
or resources.

14. **URL Programming:**

URL programming in Java involves manipulating URLs (Uniform Resource Locators) to perform
various networking tasks such as opening connections to remote servers, downloading resources, or
parsing URL components like protocol, host, port, path, etc. Java provides the `java.net.URL` class for
working with URLs.

15. **Java Program to Display Name of Currently Executing Thread:**


```java

public class Main {

public static void main(String[] args) {

Thread.currentThread().setName("Main Thread");

System.out.println("Currently executing thread: " + Thread.currentThread().getName());

```

16. **Java Program to Calculate Factorial of a Number using Sleep Method:**

```java

public class FactorialCalculator {

public static void main(String[] args) {

int number = 5; // Number whose factorial to calculate

long factorial = 1;

for (int i = 1; i <= number; i++) {

factorial *= i;

try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Factorial of " + number + " is " + factorial);

```

17. **Socket Program in Java to Check Prime Number:**


[See here for a sample code to achieve this
task](https://gist.github.com/dhuman786/3b6cd4aa1d6a21c85468a4d2deae45b8)

18. **Java Program to Display IPAddress and Name of Client Machine:**

[See here for a

sample code to achieve this


task](https://gist.github.com/dhuman786/a4a8456b23f1e47b41ed143d1cf4fd00)

19. **Java Program to Display Date and Time of Server Machine on Client Machine:**

[See here for a sample code to achieve this


task](https://gist.github.com/dhuman786/77e96d8de7e2b5f0ad2a1729b36c1c87)

20. **Java Program to Delete Details of Students Whose Initial Character of Their Name is 'S':**

[See here for a sample code to achieve this


task](https://gist.github.com/dhuman786/a5a2d27274ff306460c81de9e233f22f)

You might also like