Advance_Java_answers
Advance_Java_answers
Ans : The Collection Framework in Java is a set of classes and interfaces that
provide a unified architecture to store, retrieve, and manipulate a group of
objects efficiently. It is part of the java.util package and provides ready-to-
use data structures like List, Set, Queue, and Map.
Key Features:
Key-Value Mapping: Each key is mapped to a specific value.
Unique Keys: No duplicate keys allowed.
Efficient Lookups: Provides fast retrieval of values based on keys.
--------------------------------------------------
✅ Doubly Linked Structure – Each node has references to the previous and next
✅
nodes.
Fast Insertions/Deletions – O(1) complexity for adding/removing elements from
✅✅
the beginning or middle.
Implements List and Deque – Supports queue and stack operations.
Allows Duplicates & Nulls – Just like ArrayList.
--------------------------------------------------
✅✅
Key Features:
Read-Only Access – Cannot modify elements during traversal.
6. What is TreeSet?
Ans : TreeSet is a class in Java’s Collection Framework that implements the Set
interface using a Red-Black Tree. It stores unique elements in sorted order and
does not allow duplicates.
Features of TreeSet:
Sorted Order: Automatically sorts elements in ascending order (natural
ordering).
No Duplicates: Ensures that no duplicate elements are stored.
Implements NavigableSet: Supports navigation methods like higher(), lower(),
ceiling(), floor().
Performance: Operations like add, remove, and search have O(log n) time
complexity due to the Red-Black Tree structure.
--------------------------------------------------
Key Points:
Priority Range: The thread priority is represented by an integer value between
Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10), with a default value of
Thread.NORM_PRIORITY (5).
Thread Scheduling: Threads with higher priority are generally executed before
threads with lower priority, but the actual scheduling depends on the underlying
operating system's thread scheduler.
Non-Preemptive Nature: Java's thread priority does not guarantee exact behavior,
as thread scheduling is ultimately controlled by the operating system.
--------------------------------------------------
Key Points:
Used with Synchronized Blocks: notifyAll() can only be called from within a
synchronized block or method.
Wakes All Waiting Threads: It notifies all threads that are waiting on the same
object's monitor to wake up and compete for the lock again.
Thread Communication: It is typically used in scenarios where multiple threads
are waiting for a condition to change, and once that condition is met, all
waiting threads should proceed.
--------------------------------------------------
2. Runnable State
The thread enters the runnable state after calling start(), but it is not
necessarily running.
In this state, the thread is eligible to run, but it may not be running
immediately due to CPU scheduling.
It may be running or waiting for the CPU to execute its code.
Threads can enter this state by calling start() or if they return to this state
after sleeping or waiting.
4. Waiting State
A thread enters the waiting state when it is waiting for another thread to
perform a particular action.
A thread can be placed in this state by calling methods like wait(), join(), or
sleep() (for a specific time).
The thread will remain in the waiting state until it is notified, the specified
time has elapsed, or the action it is waiting for occurs.
1)java.sql
The core package for JDBC, containing classes and interfaces for database
connections, SQL execution, and result processing.
Key classes and interfaces:
Connection – Establishes a connection to the database.
Statement – Executes SQL queries.
PreparedStatement – Precompiled SQL queries for efficiency.
ResultSet – Represents the result of a query.
SQLException – Handles database-related exceptions.
DriverManager – Manages database drivers.
DataSource – Provides an alternative to DriverManager for establishing a
connection.
2)javax.sql
Contains advanced features for JDBC, typically used for connection pooling and
data source management.
Key classes and interfaces:
Atomicity:
The entire transaction is treated as a single atomic unit. This means that
either all operations within the transaction are executed successfully, or none
are. If any part of the transaction fails, the entire transaction is rolled
back.
Consistency:
A transaction takes the database from one consistent state to another. After the
transaction is completed, the database must be in a valid state according to its
rules, constraints, and integrity checks.
Isolation:
Transactions are isolated from each other. This means that the operations of one
transaction are not visible to other transactions until the transaction is
committed. This prevents data inconsistencies in concurrent environments.
Durability:
Once a transaction is committed, the changes made to the database are permanent.
Even in the case of system crashes, the changes will not be lost.
In JDBC, metadata refers to information about the database itself (e.g., tables,
columns, supported SQL features). The DatabaseMetaData and ResultSetMetaData
classes are commonly used to retrieve this metadata.
1. DatabaseMetaData:
Used to retrieve information about the database's structure, such as its tables,
columns, supported features, etc.
Example methods:
getTables(): Returns information about tables in the database.
getColumns(): Provides information about columns in a specified table.
getDatabaseProductName(): Retrieves the name of the database product.
2. ResultSetMetaData:
Provides metadata about the result set returned by a query (e.g., number of
columns, column names, data types).
Example methods:
getColumnCount(): Gets the number of columns in the result set.
getColumnName(int columnIndex): Gets the name of a column.
getColumnType(int columnIndex): Gets the data type of a column.
--------------------------------------------------
Iterator:
The Iterator interface provides methods to iterate over elements in a collection
(typically List, Set, etc.). It allows you to traverse the collection in a
forward direction and perform actions like removing elements during iteration.
ListIterator:
The ListIterator is an extension of the Iterator interface, specifically
designed for List collections (such as ArrayList, LinkedList, etc.). It allows
both forward and backward iteration, and also provides more powerful features,
like modifying elements and adding new elements during iteration.
hasPrevious():
Returns true if there is an element before the current position (unique to
ListIterator).
previous():
Returns the previous element in the list (unique to ListIterator).
add(E e):
Adds an element to the list at the current position (unique to ListIterator).
set(E e):
Replaces the last element returned by next() or previous() with the specified
element (unique to ListIterator).
-------
Key Differences:
Direction of Iteration:
Iterator: Can only iterate forward.
ListIterator: Can iterate both forward and backward.
Modification:
Iterator: Can remove elements during iteration but cannot modify or add
elements.
ListIterator: Can add, modify, and remove elements during iteration.
--------------------------------------------------
Advantages of Multithreading:
Improved Performance and Responsiveness:
Multithreading allows parts of a program to run concurrently, improving overall
performance by utilizing the CPU more efficiently.
In user interface (UI) applications, multithreading ensures that the UI remains
responsive while other tasks (like background data processing) are running.
Cost-Efficiency:
Creating and managing threads is less resource-intensive than creating separate
processes. Threads are lightweight, meaning they require less memory and
resources.
Asynchronous Execution:
Multithreading allows for asynchronous execution, where tasks can be carried out
in the background without blocking the main thread. For example, network
requests or file operations can be handled without freezing the main program.
Scalability:
As the number of cores in processors increases, the performance benefits of
multithreading scale significantly. This enables applications to handle more
tasks concurrently and efficiently.
--------------------------------------------------
Key Differences:
Statement:
Executes simple SQL queries or commands directly. SQL queries are compiled and
executed every time they are run, which can be inefficient and prone to errors
in case of repeated execution of the same query.
PreparedStatement:
A precompiled SQL query that allows for parameterized queries, making it more
efficient and secure. The SQL query is compiled only once and can be executed
multiple times with different parameter values.
A ResultSet object acts as a cursor that points to the current row of data in
the result set. You can use it to iterate over the rows and retrieve column
values of each row.
Dynamic Navigation:
You can use methods to move to a specific row (e.g., absolute(), first(),
last()) or to navigate one row at a time (e.g., next(), previous()).
--------------------------------------------------
In simple terms, JDBC drivers allow Java applications to send SQL commands to a
database and retrieve the results.
Conclusion
Type-4 drivers are the most commonly used due to their high performance,
platform independence, and ease of deployment.
Type-3 drivers are useful when you need to connect to multiple databases without
worrying about database-specific drivers.
Type-2 and Type-1 drivers are less common today, but they are still used in
certain legacy systems or specific configurations.
--------------------------------------------------
21. List any two methods for creating transaction.
Ans : Two Methods for Creating Transactions in JDBC
In JDBC, a transaction is a sequence of SQL operations executed as a single unit
of work. Transactions ensure data integrity and consistency by allowing
operations like commit and rollback to control the transaction flow. There are
two main ways to manage transactions in JDBC:
--------------------------------------------------
23. What is savepoint? What is its use?
Ans : A Savepoint is a mechanism in JDBC that allows you to set intermediate
points within a transaction. It enables you to mark a specific point in a
transaction so that you can roll back to that point if something goes wrong,
without affecting the entire transaction. This allows for more granular control
over the transaction process.
Use of Savepoint:
Partial Rollback: When working with complex transactions that involve multiple
operations, a savepoint allows you to rollback to an intermediate point in the
transaction, rather than rolling back the entire set of operations. This helps
prevent losing all changes when only part of the transaction fails.
Error Handling: If an error occurs during a transaction, you can use a savepoint
to backtrack to a point where the transaction was still in a valid state. You
can then correct the error and proceed with the rest of the transaction.
--------------------------------------------------
25. Compare thread and process. Any two points.
Ans : Comparison between Thread and Process
Key Point: Threads share the same memory space within a process, while
processes have their own independent memory.
Key Point: Creating threads is faster and consumes fewer resources than
creating new processes.
--------------------------------------------------
26. Give the purpose of synchronization. (Question 27 is duplicate)
Ans : Synchronization is used in Java to control access to shared resources by
multiple threads. Its primary purpose is to ensure that only one thread can
access a particular section of code (or resource) at a time, preventing data
inconsistency and race conditions in concurrent environments.
Example: If two threads try to increment the same counter at the same time,
the final value might not be correct unless synchronization is used.
--------------------------------------------------
Summary of Differences:
- Comparator is used for sorting and defining the order of elements in a
collection, whereas Enumeration is used for iterating over elements in legacy
collections.
- Comparator allows custom ordering of objects but does not modify the elements,
while Enumeration allows iteration but does not support modifying the
collection.
- Comparator is still widely used for sorting, while Enumeration is considered
outdated, replaced by Iterator.
--------------------------------------------------
29. Write a program to display “BYE CORONA…” message n times using Runnable
interface.
import java.util.Scanner;
public ByeCorona(int n) {
this.n = n;
}
@Override
public void run() {
for (int i = 1; i <= n; i++) {
System.out.println(i + ". BYE CORONA...");
try {
Thread.sleep(500); // Adding a slight delay for better
visualization
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) { // Each thread prints 5 times
System.out.println(Thread.currentThread().getName() + ": " + message
+ " (" + i + ")");
try {
Thread.sleep(500); // Simulate processing time
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "
interrupted.");
}
}
}
}
// Creating threads
Thread thread1 = new Thread(task1, "Thread-A");
Thread thread2 = new Thread(task2, "Thread-B");
Thread thread3 = new Thread(task3, "Thread-C");
// Starting threads
thread1.start();
thread2.start();
thread3.start();
}
}
--------------------------------------------------