Advanced JAVA-10 marks
Advanced JAVA-10 marks
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
Active: When a thread invokes the start() method, it moves from the new state to
the active state. The active state contains two states within it: one is runnable, and
the other is running.
History of Java
o Runnable: A thread, that is ready to run is then moved to the runnable state.
In the runnable state, the thread may be running or may be ready to run at
any given instant of time. It is the duty of the thread scheduler to provide the
thread time to run, i.e., moving the thread the running
state. A program implementing multithreading acquires a fixed slice of time
to each individual thread. Each and every thread runs for a short span of time
and when that allocated time slice is over, the thread voluntarily gives up the
CPU to the other thread, so that the other threads can also run for their slice
of time. Whenever such a scenario occurs, all those threads that are willing
to run, waiting for their turn to run, lie in the runnable state. In the runnable
state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.
For example, a thread (let's say its name is A) may want to print some data from
the printer. However, at the same time, the other thread (let's say its name is B) is
using the printer to print some data. Therefore, thread A has to wait for thread B to
use the printer. Thus, thread A is in the blocked state. A thread in the blocked state
is unable to perform any execution and thus never consume any cycle of the
Central Processing Unit (CPU). Hence, we can say that thread A remains idle until
the thread scheduler reactivates thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main
thread is in the waiting state. The main thread then waits for the child threads to
complete
their tasks. When the child threads complete their job, a notification is sent to the
main thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and
the chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread
(its name is A) has entered the critical section of a code and is not willing to leave
that critical section. In such a scenario, another thread (its name is B) has to wait
forever, which leads to starvation. To avoid such scenario, a timed waiting state is
given to thread B. Thus, thread lies in the waiting state for a specific span of time,
and not forever. A real example of timed waiting is when we invoke the sleep()
method on a specific thread. The sleep() method puts the thread in the timed wait
state. After the time runs out, the thread wakes up and start its execution from
when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
oWhen a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead
thread.
In Java, thread priorities are used to indicate the relative importance of one thread
compared to another within the same program. Thread priorities can influence how
the operating system schedules threads for execution, but they do not guarantee
strict ordering or deterministic behavior.
Synchronization
Synchronization in the context of multithreaded programming refers to the
coordination and control of multiple threads to ensure proper and safe execution in
shared resources and critical sections. Without synchronization, when multiple
threads access and manipulate shared data concurrently, it can lead to race
conditions, data corruption, and unexpected behavior. Synchronization
mechanisms prevent these issues by ensuring that only one thread can access a
critical section of code or a shared resource at a time.
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
9) Explain the difference between Thread class and Runnable interface.
In Java, both the Thread class and the Runnable interface are used to create and
manage threads for concurrent execution. However, they have distinct purposes
and usage patterns. Let's delve into the differences between the two:
Thread Class:
1. Inheritance: The Thread class is a concrete class in Java's java.lang package.
When you want to create a new thread, you can directly subclass the Thread
class and override its run() method, which contains the code that the thread
will execute.
2. Limitation: Java only supports single inheritance, so if you extend the
Thread class, you cannot extend another class, limiting your flexibility
in
terms of code reuse.
3. Thread Control: Since the Thread class encapsulates both the thread's
behavior and its management, it provides methods to directly control the
thread, such as start( to begin execution and join() to wait for the thread to
complete. )
4. Thread Instance: Each thread corresponds to an instance of the Thread class.
This means that if you want to create multiple threads, you need to create
multiple instances of the Thread class.
5. Less Flexible Resource Sharing resources between threads created
using the Thread class can be more challenging, as the thread instances
themselves encapsulate both behavior and execution.
Stream Filtering:
Stream filtering refers to the process of extracting, modifying, or manipulating
specific elements from a data stream based on certain criteria. Data streams can be
sequences of characters, bytes, or any other type of data that can be processed
sequentially. Stream filtering is a common technique used to process large datasets
efficiently without loading the entire dataset into memory at once.
In Java, stream filtering is typically associated with the Java Streams API
introduced in Java 8. Java Streams provide a powerful and functional way to
process collections and other data sources. Streams allow you to apply various
operations such as filtering, mapping, sorting, and reducing on data in a concise
and expressive manner.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
In this example, the filter operation is used to select only the even numbers from
the list of integers.
Piping:
Piping refers to the practice of connecting the output of one process or function as
the input to another, forming a chain of processing steps. Each step in the pipeline
performs a specific operation on the data and passes the modified data to the next
step. Piping is a powerful way to combine multiple operations into a single
sequence, making complex data transformations more manageable and readable.
In this example:
The result is a new list containing the filtered, transformed, and sorted words.
While this isn't exactly the same as piping in Unix shells, it offers a similar concept
of chaining operations to process data. Java's Stream API provides a powerful and
expressive way to achieve such data transformations in a functional and efficient
manner.
In summary, Swing builds upon AWT and provides a more extensive and flexible
set of GUI components, a pluggable look and feel mechanism, and a more
advanced event handling model. Swing components are lightweight and platform-
independent, offering greater consistency across different operating systems.
Despite the emergence of newer UI frameworks like JavaFX, Swing is still widely
used and supported in Java applications.
import javax.swing.*;
frame.pack();
frame.setVisible(true);
});
}
}
In this example, a basic Swing application creates a JFrame window with a JLabel
component.
Swing has been a fundamental part of Java GUI development for many years.
While newer UI frameworks like JavaFX have gained popularity, Swing remains
relevant and continues to be used in various applications and projects.
13) Write about the key features of JavaSwing.
Java Swing is a GUI (Graphical User Interface) toolkit for Java applications. It
provides a rich set of components and tools to create interactive and visually
appealing graphical user interfaces. Swing is built on top of the Abstract Window
Toolkit (AWT) but offers several enhancements and improvements over AWT.
Here are the key features of Java Swing:
1. Lightweight Components:
Swing components are lightweight and platform-independent. Unlike AWT, which
relies on native components, Swing components are implemented purely in Java.
This ensures consistent behavior and appearance across different platforms.
4. Layout Managers:
Swing provides layout managers that help you arrange components within
containers. Layout managers handle tasks like component positioning, sizing, and
alignment. Common layout managers include FlowLayout, BorderLayout,
GridLayout, and BoxLayout.
5. Customizability:
Swing components are highly customizable. You can modify their appearance by
setting properties, changing colors, fonts, and other visual attributes. Additionally,
you can create custom components by extending existing ones or implementing
Swing interfaces.
6. Event Handling:
Swing offers a flexible event handling model. You can attach event listeners to
components to respond to user interactions such as button clicks, mouse events,
and keyboard input. This model enables more precise control over how events are
processed.
7. Double Buffering:
Swing components use double buffering by default, which reduces flickering and
enhances the rendering of complex UIs. Double buffering involves rendering
components off-screen before displaying them, resulting in smoother animations
and improved performance.
8. Thread Safety:
Swing follows a single-threaded model, where all UI-related operations must be
performed on the event dispatch thread (EDT). Swing provides mechanisms to
ensure thread safety and synchronization of UI updates, helping to prevent
concurrent access issues.
11. Accessibility:
Swing components include built-in accessibility features, allowing visually
impaired users to interact with applications using screen readers and other assistive
technologies.
frame.setVisible(true);
}
}
1. The main method initializes the Swing components on the Event Dispatch
Thread (EDT) using SwingUtilities.invokeLater() to ensure proper GUI
initialization.
2. The createAndShowGUI method sets up the main frame for the user
registration form with a 6x2 grid layout.
3. Labels, text fields, radio buttons, and a button are created to gather user
input.
4. Event listeners are added to the submit button to process form data
when clicked.
5. Form data (name, email, password, gender) is collected from
the components.
6. The form data is printed to the console for demonstration purpose.
import java.sql.*;
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create a statement
Statement statement = connection.createStatement();
// Close resources
resultSet.close();
statement.close();
connection.close();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, we use the MySQL JDBC driver to connect to a MySQL database,
execute a SELECT query, and print the retrieved data. The general workflow
applies to other database systems as well.
JDBC is a foundational technology for Java applications that need to interact with
databases. It provides a standardized way to manage connections, execute queries,
and handle data, making it an essential tool for building database-driven
applications.
1. Driver Manager:
The DriverManager class acts as a central hub for managing database drivers. It's
responsible for loading and registering appropriate database drivers dynamically.
The driver manager allows applications to work with different database systems
without needing to modify code extensively. You use the DriverManager to obtain
a Connection to the database using the URL, username, and password.
2. Connection Pooling:
JDBC encourages the use of connection pooling to manage database connections
efficiently. Connection pooling involves creating and maintaining a pool of
database connections that can be reused. This minimizes the overhead of
establishing and closing connections for every database operation, improving
performance and resource management.
3. Resource Management:
JDBC emphasizes proper resource management to avoid resource leaks and
potential performance degradation. Resources like Connection, Statement, and
ResultSet must be explicitly closed when they are no longer needed. Failing to
close these resources can lead to memory leaks and increased resource
consumption.
4. SQL Statements:
JDBC supports three types of SQL statements: Statement, PreparedStatement, and
CallableStatement . Each type has its own purpose and usage:
6. Error Handling:
JDBC uses the SQLException class to handle database-related errors. Handling
exceptions is crucial for diagnosing and resolving issues that may occur during
database operations. Proper error handling helps ensure robustness and stability in
your applications.
7. Data Types
Mapping:
JDBC provides mappings between Java data types and SQL data types, allowing
seamless communication between the application and the database. This mapping
ensures that data conversions are handled correctly and transparently.
8. Batch
Processing:
JDBC supports batch processing, where multiple SQL statements are grouped
together and executed in a batch. This can significantly improve performance when
you need to perform repetitive tasks, such as inserting multiple rows into a table.
9. SQL Injection
ByPrevention:
using parameterized queries with PreparedStatement, JDBC helps prevent SQL
injection attacks. Parameterized queries separate data from the query, making it
harder for attackers to manipulate SQL statements.
10. Transaction Management:
JDBC provides mechanisms for managing transactions, ensuring the consistency
and integrity of data. You can explicitly commit or roll back transactions using the
commit() and rollback() methods on the Connection object.
1. Data Storage and Retrieval: Applications often need to store and retrieve
data from databases to maintain information about users, products,
transactions, etc.
2. Reporting and Analysis: Database connectivity enables applications to
retrieve and analyze data for generating reports, statistics, and insights.
3. Authentication and Authorization: User authentication and authorization
information is often stored in databases, requiring connectivity for user
management.
4. E-commerce and Transactions: Online stores and financial applications rely
on database connectivity to manage orders, payments, and inventory.
5. Content Management: Content management systems use databases to store
articles, images, videos, and other media files.
Steps in Database Connectivity:
1. Loading the Driver: To establish a connection to a database, you need to
load the appropriate JDBC driver class. The driver class is provided by the
database vendor and implements the JDBC standard.
2. Establishing Connection: Once the driver is loaded, you use the
DriverManager.getConnection() method to establish a connection to the
database. You provide the connection URL, username, and password as
arguments.
3. Creating Statements: After obtaining a connection, you create a Statement or
PreparedStatement object. These objects allow you to execute SQL queries
and commands against the database.
4. Executing Queries: You execute SQL queries using the executeQuery()
method for SELECT statements and executeUpdate() for INSERT,
UPDATE, and DELETE statements. The results of a SELECT query are
returned as a ResultSet object.
5. Processing Results: When you execute a SELECT query, the result set
contains the retrieved data. You can iterate through the result set and
extract values using methods like getString(), getInt(), etc.
6. Closing Resources: After using the database resources, it's crucial to close
them properly to release database connections and resources. Failing to close
resources can lead to resource leaks.
7. Handling Exceptions: Database operations can result in exceptions due to
various reasons such as connection issues, query errors, or database
constraints. Proper error handling using try-catch blocks ensures graceful
error reporting and recovery.
JDBC and Database Connectivity:
JDBC is a Java API that provides a standard way to connect to relational databases
and perform database operations using Java code. It simplifies database
connectivity by offering a consistent interface for different databases. Developers
use JDBC to execute SQL queries, retrieve data, update records, and manage
transactions.
CLIENT SIDE:
import java.io.*;
import java.net.*;
// Read messages from the user and send them to the server
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String message;
while (true) {
System.out.print("You: ");
message = userInput.readLine(); // Read user input
out.println(message); // Send message to the server
if (message.equalsIgnoreCase("bye")) {
break; // Exit the loop if the user types "bye"
}
// Close resources
userInput.close();
in.close();
out.close();
socket.close();
} catch (IOException e)
{ e.printStackTrace();
}
}
}
SERVER SIDDE:
import java.io.*;
import java.net.*;
// Close resources
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e)
{ e.printStackTrace();
}
}
}
19) Explain Secure sockets.
Secure Socket Layer (SSL) provides security to the data that is transferred
between web browser and server. SSL encrypts the link between a web server and
a browser which ensures that all data passed between them remain private and
free from attack.
Secure Socket Layer Protocols:
SSL record protocol
Handshake protocol
Change-cipher spec protocol
Alert protocol
SSL Protocol Stack:
The SSL (Secure Sockets Layer) record protocol is a key component of the
SSL/TLS (Transport Layer Security) protocol suite, which is used to secure data
transmission over the internet. The SSL record protocol is responsible for
fragmenting, compressing (optional), encrypting, and authenticating data to ensure
the confidentiality, integrity, and authenticity of information exchanged between a
client and a server. It operates at the transport layer of the OSI model and is used to
establish secure communication channels between web browsers and web servers,
among other applications.
HANDSHAKE PROTOCOL:
The handshake protocol is an essential part of the SSL/TLS (Secure Sockets
Layer/Transport Layer Security) protocol suite, which is used to establish secure
communication channels over the internet. The handshake protocol's primary
purpose is to enable the client and server to authenticate each other, negotiate
encryption algorithms, and establish session keys for secure data exchange.
ALERT PROTOCOL:
The Alert Protocol is a crucial component of the SSL/TLS (Secure Sockets
Layer/Transport Layer Security) protocol suite, used to establish secure
communication channels over the internet. The primary purpose of the Alert
Protocol is to provide a means for communicating various alert and error messages
between the client and server during the SSL/TLS handshake and data exchange
phases. These alert messages can inform both parties about issues that may arise
during the secure communication.
TCP is commonly used for applications that require reliable and error-checked
communication, such as web browsing, email, file transfers, and most online
services. While TCP provides a high level of reliability, it may introduce some
additional overhead due to its connection-oriented nature and the various
mechanisms in place to ensure data integrity and order.
3. Scalability: These applications are built in a way that allows them to handle
more work by adding more computers to the network. This is like having more
workers to do a job when it gets busier.
4. Reliability and Fault Tolerance: Even if one of the computers in the network
fails, the application keeps working. It's like having backup plans so that the whole
system doesn't break if something goes wrong.
7. Security: Since the computers are connected over a network, security is crucial.
It's like making sure that only authorized people can access your files and
information.
1. Client:
The client is a device or software application that requests services,
resources, or data from a server.
It can be a personal computer, smartphone, tablet, or any other device
capable of connecting to a network.
Clients are typically responsible for presenting information to
the user, such as user interfaces, and processing user input.
They send requests to servers and receive responses.
2. Server:
The server is a powerful computer or software application that
provides services, resources, or data to clients over a network.
Servers are designed to handle multiple client requests
simultaneously, making them capable of serving multiple clients
concurrently.
They store and manage data, perform calculations, and execute tasks on
behalf of clients.
Servers are often dedicated to specific tasks, such as web servers,
database servers, email servers, file servers, and more.
Scalability: Servers can handle multiple clients, making it easy to scale the
system as the number of clients increases.
Centralized Data Management: Servers centralize data storage, making it
easier to maintain and secure data.
Resource Sharing: Clients can access and share resources hosted on servers,
such as files, databases, and services.
Client Diversity: Clients can be diverse, ranging from different platforms and
devices, as long as they can communicate with the server using standard
protocols.
To use Java Servlets, you need a Java servlet container, such as Apache Tomcat,
Jetty, or WildFly, which provides the runtime environment for servlet execution.
Servlets are a fundamental building block for developing Java-based web
applications, and they are commonly used in conjunction with other Java EE
technologies like JSP, EJB, and JDBC to create robust, scalable, and feature-rich
web applications.
In some architectures, you may find additional tiers, such as caching layers,
security layers, or messaging layers, depending on the specific requirements of the
application.