Java Notes
Java Notes
UNIT-1
2
Example
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Applications
There are many devices where Java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
_____________________________________________________________________
1.2 EVENT AND LISTENER (JAVA EVENT HANDLING)
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
● Foreground Events
● Background Events
3
1. Foreground Events
Foreground events are the events that require user interaction to generate.
Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background
events. Examples are operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an
event occurs. To handle the events, Java follows the Delegation Event model.
Delegation Event Model
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax: addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
4
Event Classes in Java
5
component.
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized(), componentShown()
ComponentListener
componentMoved(), componentHidden()
ItemListener itemStateChanged()
MouseWheelListener mouseWheelMoved()
6
TextListener textChanged()
windowActivated(), windowDeactivated()
WindowListener windowOpened(), windowClosed()
windowClosing(), windowIconified()
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered
listener.
4. The method executes and returns the result.
Code-Approaches
The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
Event Handling Within Class
In this approach, the event handling code is written within the same class that contains
the event source. The class implements the appropriate listener interface & provides the
implementation for the corresponding event-handling method.
7
// Event handling within the class
import java.awt.*;
import java.awt.event.*;
class GFGTop extends Frame implements ActionListener {
TextField textField;
GFGTop()
{
textField = new TextField();
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
button.addActionListener(this);
add(textField);
add(button);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
textField.setText("GFG!");
}
public static void main(String[] args)
{
new GFGTop();
}
}
8
Output
9
{
new GFG2();
}
}
import java.awt.event.*;
class Other implements ActionListener {
GFG2 gfgObj;
Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}
public void actionPerformed(ActionEvent e)
{
gfgObj.textField.setText("Using Different Classes");
}
}
Output:
10
// Event handling by Anonymous Class
import java.awt.*;
import java.awt.event.*;
class GFG3 extends Frame {
TextField textField;
GFG3()
{
textField = new TextField();
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
textField.setText("Anonymous");
}
});
add(textField);
add(button);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
new GFG3();
}
}
11
Output
Handling anonymously
____________________________________________________________________
1.3 Java Architecture (JVM, JRE, JDK)
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the
process of interpretation and compilation. It defines all the processes involved in
creating a Java program. Java Architecture explains each and every step of how a
program is compiled and executed.
Java Architecture can be explained by using the following steps:
The following figure represents the Java Architecture in which each step is elaborate
graphically.
12
Components of Java Architecture
The Java architecture includes the three main components:
ClassLoader: ClassLoader is a subsystem used to load class files. ClassLoader first loads
the Java code whenever we run it.
Class Method Area: In the memory, there is an area where the class data is stored
during the code's execution. Class method area holds the information of static
variables, static methods, static blocks, and instance methods.
Heap: The heap area is a part of the JVM memory and is created when the JVM starts
up. Its size cannot be static because it increases or decreases during the application
runs.
13
Stack: It is also referred to as thread stack. It is created for a single execution thread.
The thread uses this area to store the elements like the partial result, local variable,
data used for calling method and returns etc.
Native Stack: It contains the information of all the native methods used in our
application.
Execution Engine: It is the central part of the JVM. Its main task is to execute the byte
code and execute the Java classes. The execution engine has three main components
used for executing Java classes.
○ Interpreter: It converts the byte code into native code and executes. It
sequentially executes the code. The interpreter interprets continuously and
even the same method multiple times. This reduces the performance of the
system, and to solve this, the JIT compiler is introduced.
○ JIT Compiler: JIT compiler is introduced to remove the drawback of the
interpreter. It increases the speed of execution and improves performance.
○ Garbage Collector: The garbage collector is used to manage the memory, and it
is a program written in Java. It works in two phases, i.e., Mark and Sweep. Mark
is an area where the garbage collector identifies the used and unused chunks of
memory. The Sweep removes the identified object from the Mark
14
1.4 Thread Concept in Java
A Thread is a very light-weighted process, or the smallest part of the process that
allows a program to operate more efficiently by running multiple tasks simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept
in Java. All the tasks are executed without affecting the main program. In a program or
process, all the threads have their own separate path for execution, so each thread of a
process is independent.
Another benefit of using thread is that if a thread gets an exception or an error at the
time of its execution, it doesn't affect the execution of the other threads. When
multiple threads are executed in parallel at the same time, this process is known as
Multithreading.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:
15
4) Blocked : A thread is in the Blocked state when it is waiting for resources.
5) Terminated : A thread comes in a terminated state when at any given time, it halts
its execution immediately.
Creating Thread
A thread is created either by
● Creating or Implementing" the Runnable Interface (or)
● Extending the Thread class.
These are the only two ways through which we can create a thread.
Thread Class
A Thread class has several methods and constructors which allow us to perform various
operations on a thread. The Thread class extends the Object class. The Object class
implements the Runnable interface. The thread class has the following constructors
that are used to perform various operations.
○ Thread()
○ Thread(Runnable, String name)
○ Thread(Runnable target)
○ Thread(ThreadGroup group, Runnable target, String name)
○ Thread(ThreadGroup group, Runnable target)
○ Thread(ThreadGroup group, String name)
○ Thread(ThreadGroup group, Runnable target, String name, long stackSize)
16
ThreadExample2(String name) {
this.name = name;
System.out.println("A New thread: " + this + " is created\n");
start(); // Start the thread
}
try {
Thread.sleep(8000);
} catch (InterruptedException exception) {
System.out.println("Interruption occurs in Main Thread");
}
System.out.println("We are exiting from Main Thread");
}
}
Output:
17
Creating thread by implementing the runnable interface
class NewThread implements Runnable {
String name;
Thread thread;
NewThread (String name)
{ this.name = name;
thread = new Thread(this, name);
System.out.println( "A New thread: " + thread + "is created\n" );
thread.start();
}
public void run()
{
try {
for(int j = 5; j > 0; j--) {
System.out.println(name + ": " + j);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{ System.out.println(name + " thread Interrupted");
}
System.out.println(name + " thread exiting.");
}
}
class ThreadExample2 {
public static void main(String args[]) {
new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
Thread.sleep(8000);
} catch (InterruptedException exception) {
System.out.println("Interruption occurs in Main Thread");
}
18
System.out.println("We are exiting from Main Thread");
}
}
Output:
19
count simultaneously, leading to incorrect results.
Thread Pools
Creating and managing threads individually can be inefficient, especially in applications
with a large number of tasks. Thread pools provide a solution by reusing existing
threads to execute multiple tasks, thereby reducing the overhead associated with
thread creation and destruction.
Java's ExecutorService and ThreadPoolExecutor classes facilitate the creation and
management of thread pools:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new MyRunnable());
Thread Priorities
Java allows developers to assign priorities to threads, influencing the scheduling
decisions made by the JVM's thread scheduler. Threads with higher priorities are given
preference by the scheduler, but thread priorities are only hints and not strict
guarantees of execution order.
Thread thread1 = new Thread();
thread1.setPriority(Thread.MAX_PRIORITY);
Thread thread2 = new Thread();
thread2.setPriority(Thread.MIN_PRIORITY);
_____________________________________________________________________
1.5 Java Networking
Java networking refers to writing programs that execute across multiple devices n
which the devices are all connected to each other using a network.
Advantages of Java Networking
Creating server-client applications
Implementing networking protocols
Implement socket programming
Creating web services
Package Used in Networking
The java.net package of the J2SE APIs contains a collection of classes and interfaces
that provide the low-level communication details, allowing you to write programs that
focus on solving the problem at hand.
The java.net package provides support for the two common network protocols
● TCP − TCP stands for Transmission Control Protocol, which allows for reliable
20
communication between two applications. TCP is typically used over the
Internet Protocol, which is referred to as TCP/IP.
● UDP − UDP stands for User Datagram Protocol, a connectionless protocol that
allows for packets of data to be transmitted between applications.
Socket Programming in Java Networking
Sockets provide the communication mechanism between two computers using TCP. A
client program creates a socket on its end of the communication and attempts to
connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and
reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class
provides a mechanism for the server program to listen for clients and establish
connections with them.
The following steps occur when establishing a TCP connection between two computers
using sockets −
● The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
● The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.
● After the server is waiting, a client instantiates a Socket object, specifying the
server name and the port number to connect to.
● The constructor of the Socket class attempts to connect the client to the
specified server and the port number. If communication is established, the
client now has a Socket object capable of communicating with the server.
● On the server side, the accept() method returns a reference to a new socket on
the server that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams.
Each socket has both an OutputStream and an InputStream. The client's OutputStream
is connected to the server's InputStream, and the client's InputStream is connected to
the server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams
at the same time. Following are the useful classes providing a complete set of methods
to implement sockets.
21
Example of Java Networking
22
Implementing Socket Server in Java
The following GreetingServer program is an example of a server application that uses
the Socket class to listen for clients on a port number specified by a command-line
argument −
Example: Socket Server
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();
}
catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
23
}
}
}
public static void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Compile the client and the server and then start the server as follows −
24
COMPONENTS OF MULTIMEDIA
The following are typical multimedia elements:
1) Text - Text appears in all multimedia projects to some extent. The text may be
presented in a variety of font styles and sizes.
2) Graphics - Graphics can be of two different types:
Bitmap - Bitmap images are authentic pictures that can be taken using
tools like digital cameras or scanners. Bitmap pictures are often not
modifiable. Memory use for bitmap pictures is high.
Vector Graphics - Computers can draw vector graphics because they just
need a little amount of memory. These images can be changed.
3) Animation - A static picture can be animated to appear to be in motion. A
continuous succession of static images shown in order is all that makes up an
animation.
4) Audio - Speech, music, and sound effects could all be necessary for a multimedia
application. They are referred to as the audio or sound component of multimedia.
Speaking is a fantastic educational tool.
5) Video - The term "video" describes a moving image that is supported by sound, such
as a television image. A multimedia application's video component conveys a lot of
information quickly. For displaying real-world items in multimedia applications,
digital video is helpful.
APPLICATIONS OF MULTIMEDIA
The typical areas where multimedia is applied are listed below.
1) For entertainment purposes - Multimedia marketing may significantly improve
the promotion of new items. Both advertising and marketing staff had their
doors opened by the economical communication boost provided by multimedia.
2) For education purposes - There are currently a lot of educational computer
games accessible. There are many more multimedia products on the market
that provide children with a wealth of in-depth knowledge and playing options.
3) For business purposes - There are several commercial uses for multimedia.
Today's team members can work remotely and for a variety of businesses. The
following facilities should be supported by the multimedia network:
Office needs
25
Records management
Employee training
Electronic mail
Voice mail
4) For marketing purposes - Multimedia marketing may significantly improve the
promotion of new items. Both advertising and promotion staff had their doors
opened by the economical communication boost provided by multimedia.
5) For banking purposes - Another public setting where multimedia is being used
more and more recently is banks. People visit banks to open savings and current
accounts, make deposits and withdrawals, learn about the bank's various
financial plans, apply for loans, and other things. Each bank wants to notify its
consumers with a wealth of information. nline and internet banking have grown
in popularity recently. These heavily rely on multimedia.
Media Techniques
There are several media techniques that can be used in Java programming:
Image Manipulation:
Java provides various libraries and classes for loading, manipulating, and saving images.
For example, the javax.imageio package allows developers to read and write images in
different formats, while java.awt.image package offers classes for performing
operations like scaling, cropping, and filtering on images.
Audio Playback:
Java Sound API enables developers to play audio files of different formats. It provides
classes like Clip and AudioInputStream to load and manipulate audio data. JavaFX also
provides media classes for playing audio files, along with advanced features such as
playback controls and volume management.
Video Playback:
JavaFX has built-in media capabilities, which allow developers to play video files in
different formats. The javafx.scene.media package provides classes like MediaPlayer
and MediaView for handling video playback. By using these classes, you can control
video playback, handle events, and even apply visual effects to the video.
Animation:
Java provides several libraries and frameworks that support animation. For example,
JavaFX provides a powerful animation framework with classes like Animation, Timeline,
and KeyFrame. These classes allow you to create smooth animations by specifying
26
time-based actions and transitions.
3D Graphics:
Java 3D API provides support for creating and manipulating 3D graphics in Java. With
Java 3D, you can create complex 3D objects, apply textures and lighting effects, and
even perform animations in three-dimensional space.
Web Content Integration:
JavaFX provides a WebView class that enables developers to embed web content in
Java applications. This allows you to integrate media elements like images, audio, and
video from web sources into your Java application.
Java Program to Play an Audio File
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class AudioPlayer {
public static void main(String[] args) {
File audioFile = new File("path_to_your_audio_file.wav");
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
Clip audioClip = AudioSystem.getClip();
audioClip.open(audioStream);
audioClip.start();
System.out.println("Playing audio...");
Thread.sleep(audioClip.getMicrosecondLength() / 1000);
audioClip.close();
System.out.println("Audio playback finished.");
}
catch (UnsupportedAudioFileException | IOException | LineUnavailableException |
InterruptedException e) {
e.printStackTrace();
}
}
}
_________________________________________________________________
27
28
S.
N Question a) Option b) Option c) Option d) Option
o
What does Java Desktop Mobile
Server Web
1 ME primarily application application
applications applications
develop? s s
Which of the
Desktop
applications Mobile Server Web
2 application
run on the applications applications applications
s
server?
Which feature
of Java allows Multithreadi Interoperabilit
3 Portability Object-oriented
it to run on any ng y
platform?
What type of
event requires Foreground Background
4 Action event Mouse event
user event event
interaction?
What type of
event does not Foregroun Background
5 Action event Mouse event
require user d event event
interaction?
What does
A keypress
KEYEVENT A mouse A background A change in
6 on the
represent in click task text
keyboard
Java?
Java Java Java
What does JDK
7 Developme Debugging Java Data Kit Documentatio
stand for?
nt Kit Kit n Kit
What does Write
Write Once Write Only Run Write Once
8 WORA stand Once Run
Run Around Anywhere Read Always
for in Java? Anywhere
What is the
function of a To compile To load To manage
9 To execute code
Class Loader in Java code class files memory
Java?
Which of the
A heavy- A light-
1 following best A system
weighted weighted A Java class
0 describes a event
process process
thread in Java?
29
UNIT-2
Remote Method Invocation (RMI) is an API that allows an object to invoke a method on
an object that exists in another address space, which could be on the same machine or
on a remote machine. Through RMI, an object running in a JVM present on a computer
(Client-side) can invoke methods on an object present in another JVM (Server-side).
RMI creates a public remote server object that enables client and server-side
communications through simple method calls on the server object.
Stub Object: The stub object on the client machine builds an information block and
sends this information to the server.
The block consists of
● An identifier of the remote object to be used
● Method name which is to be invoked
● Parameters to the remote JVM
Skeleton Object: The skeleton object passes the request from the stub object to the
remote object. It performs the following tasks
● It calls the desired method on the real object present on the server.
● It forwards the parameters received from the stub object to the method.
Working of RMI
The communication between client and server is handled by using two intermediate
objects: Stub object (on client side) and Skeleton object (on server-side) as also can be
depicted from below media as follows:
These are the steps to be followed sequentially to implement Interface as defined
below as follows:
1. Defining a remote interface
2. Implementing the remote interface
30
3. Creating Stub and Skeleton objects from the implementation class using rmic
(RMI compiler)
4. Start the rmiregistry
5. Create and execute the server application program
6. Create and execute the client application program.
Step 1: Defining the remote interface
The first thing to do is to create an interface that will provide the description of the
methods that can be invoked by remote clients. This interface should extend the
Remote interface and the method prototype within the interface should throw the
RemoteException.
Example:
// Creating a Search interface
import java.rmi.*;
public interface Search extends Remote
{
// Declaring the method prototype
public String query(String search) throws RemoteException;
}
Step 2: Implementing the remote interface
The next step is to implement the remote interface. To implement the remote
interface, the class should extend to UnicastRemoteObject class of java.rmi package.
Also, a default constructor needs to be created to throw the java.rmi.RemoteException
from its parent constructor in class.
// Java program to implement the Search interface
import java.rmi.*;
import java.rmi.server.*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
// Default constructor to throw RemoteException
// from its parent constructor
SearchQuery() throws RemoteException
{
super();
31
}
// Implementation of the query interface
public String query(String search)
throws RemoteException
{
String result;
if (search.equals("Reflection in Java"))
result = "Found";
else
result = "Not Found";
return result;
}
}
Step 3: Creating Stub and Skeleton objects from the implementation class using rmic
The rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton
objects. Its prototype is rmic classname. For above program the following command
need to be executed at the command prompt
rmic SearchQuery.
Step 4: Start the rmiregistry
Start the registry service by issuing the following command at the command prompt
start rmiregistry
Step 5: Create and execute the server application program
The next step is to create the server application program and execute it on a separate
command prompt.
The server program uses createRegistry method of LocateRegistry class to create
rmiregistry within the server JVM with the port number passed as an argument.
The rebind method of Naming class is used to bind the remote object to the new name.
// Java program for server application
import java.rmi.*;
import java.rmi.registry.*;
public class SearchServer
{
public static void main(String args[])
{
32
try
{
// Create an object of the interface
// implementation class
Search obj = new SearchQuery();
RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the
distributed applications in java.
Stub and Skeleton objects are used for communication between the client and server-
side.
_____________________________________________________________________
2.2 DISTRIBUTED APPLICATION ARCHITECTURE
Architecture styles in distributed systems define how components interact and are
structured to achieve scalability, reliability, and efficiency.
What are Distributed Systems?
Distributed Systems are networks of independent computers that work together to
present themselves as a unified system. These systems share resources and coordinate
tasks across multiple nodes, allowing them to work collectively to achieve common
goals.
Architecture Styles in Distributed Systems
To show different arrangement styles among computers, Architecture styles are
proposed.
34
1. Layered Architecture in Distributed Systems
● Layered Architecture in distributed systems organizes the system into
hierarchical layers, each with specific functions and responsibilities.
● This design pattern helps manage complexity and promotes separation of
concerns.
● This separation helps in managing and scaling the system more effectively.
Examples of Layered Architecture in Distributed System
Web Applications: A common example includes web applications with a presentation
layer (user interface), application layer (business logic), and data access layer (database
interactions).
Enterprise Systems: Large enterprise systems often use layered architecture to
separate user interfaces, business logic, and data management.
2. Peer-to-Peer (P2P) Architecture in Distributed Systems
● Peer-to-Peer (P2P) Architecture is a decentralized network design where each
node, or “peer,” acts as both a client and a server.
● In a P2P architecture, all nodes (peers) are equal participants in the network,
each capable of initiating and receiving requests.
● Peers collaborate to share resources, such as files or computational power,
without relying on a central server.
Examples of Peer-to-Peer (P2P) Architecture in Distributed Systems
File Sharing Networks: Systems like BitTorrent allow users to share and download files
from multiple peers, with each peer contributing to the upload and download
processes.
Decentralized Applications (DApps): Applications that run on decentralized networks,
leveraging P2P architecture for tasks like data storage and computation.
3. Data-Centric Architecture in Distributed Systems
● Data-Centric Architecture is an architectural style that focuses on the central
management and utilization of data.
● In this approach, data is treated as a critical asset, and the system is designed
around data management, storage, and retrieval processes.
● This system is used to support efficient data management and manipulation.
Examples of Data-Centric Architecture in Distributed Systems
Relational Databases: Systems like MySQL, PostgreSQL, and Oracle use Data-Centric
Architecture to manage and store structured data efficiently, providing consistent
35
access and integration across applications.
Data Warehouses: Platforms such as Amazon Redshift and Google BigQuery are
designed to centralize and analyze large volumes of data from various sources,
enabling complex queries and data analysis.
4. Service-Oriented Architecture (SOA) in Distributed Systems
● Service-Oriented Architecture (SOA) is a design paradigm in distributed systems
where software components, known as “services,” are provided and consumed
across a network.
● Each service is a discrete unit that performs a specific business function and
communicates with other services through standardized protocols.
Examples of Service-Oriented Architecture (SOA) in Distributed Systems
Enterprise Systems: SOA is commonly used to integrate various enterprise applications
such as ERP, CRM, and HR systems, allowing them to work together seamlessly.
Web Services: Many modern web applications leverage SOA principles to interact with
external services via APIs, enabling functionalities such as payment processing, data
retrieval, and authentication.
5. Event-Based Architecture in Distributed Systems
● Event-Driven Architecture (EDA) is an architectural pattern where the flow of
data and control in a system is driven by events.
● Components in an EDA system communicate by producing and consuming
events, which represent state changes or actions within the system.
Examples of Event-Based Architecture in Distributed Systems
Real-Time Analytics: Systems like stock trading platforms use EDA to process and
respond to market events in real time.
IoT Systems: Internet of Things (IoT) applications use EDA to manage and respond to
data from various sensors and devices.
Fraud Detection: Financial institutions use EDA to detect and respond to suspicious
activities or anomalies in real time.
6. Microservices Architecture for Distributed Systems
● Microservices Architecture is a design pattern where an application is composed
of small, independent services that each perform a specific function.
● These services are loosely coupled and interact with each other through
lightweight communication protocols, often over HTTP or messaging queues.
Examples of Microservices Architecture for Distributed Systems
36
E-Commerce Platforms: Platforms like Amazon use microservices to handle different
aspects of their operations, such as user authentication, payment processing, and order
management.
Financial Services: Banks and financial institutions use microservices to manage various
functions, including transaction processing, customer management, and compliance.
37
4. Stub and Skeleton:
○ Stub: Proxy on the client-side.
○ Skeleton (pre-Java 5): Dispatches calls on the server-side (replaced by
reflection in newer versions).
Steps to Define a Remote RMI Object
Step 1: Define the Remote Interface
● A remote interface extends the java.rmi.Remote interface.
● All methods must throw java.rmi.RemoteException.
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Calculator extends Remote {
// Method to add two numbers
int add(int a, int b) throws RemoteException;
// Method to subtract two numbers
int subtract(int a, int b) throws RemoteException;
}
Step 2: Implement the Remote Interface
● The implementation class must extend java.rmi.server.UnicastRemoteObject.
● Implement all methods defined in the remote interface.
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class CalculatorImpl extends UnicastRemoteObject implements
Calculator {
// Constructor
protected CalculatorImpl() throws RemoteException {
super();
}
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;
38
}
}
Step 3: Create and Register the Remote Object
● Use the java.rmi.registry.LocateRegistry class to create and bind the object to
the RMI Registry.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
// Create remote object
Calculator calculator = new CalculatorImpl();
// Bind the remote object to the RMI registry
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("CalculatorService", calculator);
System.out.println("Server is ready.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Testing the RMI Object
Client Code
● Lookup the remote object in the RMI registry and invoke its methods.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
// Lookup the registry for the remote object
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
Calculator calculator = (Calculator) registry.lookup("CalculatorService");
// Invoke methods on the remote object
39
System.out.println("Addition:"+ calculator.add(10, 5));
System.out.println("Subtraction:"+ calculator.subtract(10, 5));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Compiling and Running RMI Applications
1. Compile Classes: Use javac to compile all classes.
2. Generate Stubs (Pre-Java 5): Use the rmic tool to generate stub classes.
3. Start RMI Registry: Run rmiregistry from the command line.
4. Run Server: Start the server application.
5. Run Client: Execute the client application.
Advantages of RMI
● Easy to use and integrates seamlessly with Java.
● Abstracts underlying complexities of network communication.
● Supports object-oriented distributed programming.
_____________________________________________________________________
2.4 REMOTE OBJECT ACTIVATION
Introduction
● Remote Object Activation is a feature in Java's RMI that enables creating
remote objects on demand.
● It allows an object to be activated only when a client requests it, reducing
resource usage compared to keeping objects always in memory.
● Activation provides scalability by managing object lifecycle dynamically.
Key Concepts
1. Persistent Naming:
○ Activated objects are registered with a persistent naming service to
enable lookup even after they are deactivated.
2. Object State:
○ Objects retain their state across activations, allowing seamless
interaction for clients.
3. Activation Daemon:
○ The rmid daemon manages the activation of objects when they are
40
needed.
Components of Remote Object Activation
1. Activation Group:
○ A container for activated objects.
○ Manages the shared resources for objects in the same group.
○ Implements java.rmi.activation.ActivationGroup.
2. Activation Descriptor:
○ Provides the information needed to activate an object, such as its class
name, location, and initialization parameters.
○ Implements java.rmi.activation.ActivationDesc.
3. Activation System:
○ A central registry to manage activation groups and descriptors.
○ Implemented by the java.rmi.activation.ActivationSystem interface.
Steps to Implement Remote Object Activation
Step 1: Define the Remote Interface
● Similar to a regular RMI object, the remote interface defines the methods
accessible to clients.
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MyService extends Remote {
String getMessage() throws RemoteException;
}
Step 2: Implement the Remote Object
● The implementation class extends Activatable instead of UnicastRemoteObject.
● Use a constructor that accepts ActivationID and MarshalledObject.
import java.rmi.activation.Activatable;
import java.rmi.activation.ActivationID;
import java.rmi.RemoteException;
import java.rmi.MarshalledObject;
public class MyServiceImpl extends Activatable implements MyService {
public MyServiceImpl(ActivationID id, MarshalledObject<?> data)
throws RemoteException {
super(id, 0); // Call to superclass constructor
}
41
@Override
public String getMessage() throws RemoteException {
return "Hello, activated world!";
}
}
Step 3: Create an Activation Group
● Activation groups are required to manage the lifecycle of activated objects.
● Set up a group descriptor and register it.
import java.rmi.activation.*;
public class ActivationSetup {
public static void main(String[] args) {
try {
ActivationGroupDesc groupDesc = new ActivationGroupDesc(null, null);
ActivationGroupID groupID =
ActivationGroup.getSystem().registerGroup(groupDesc);
ActivationDesc objectDesc = new ActivationDesc(
groupID,
"MyServiceImpl",
"file://path/to/class/files",
null
);
MyService stub = (MyService) Activatable.register(objectDesc);
System.out.println("Stub registered: " + stub);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 4: Start the Activation System
Run the rmid activation daemon:
bash
rmid -J-Djava.security.policy=policyfile
Start the RMI registry:
bash
42
rmiregistry
Start the server application.
Step 5: Client Code
The client looks up the remote object as usual and invokes methods on it.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost");
MyService service = (MyService) registry.lookup("MyService");
System.out.println(service.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advantages of Activation
● Resource Efficiency: Objects are created only when needed, conserving
memory and processing power.
● Scalability: Simplifies the development of large-scale distributed systems by
dynamically managing remote objects.
● Fault Tolerance: Allows recovery and reactivation of objects in case of server
failures.
_____________________________________________________________________
2.5 SERIALIZATION AND DESERIALIZATION IN JAVA
Introduction
● Serialization: The process of converting an object into a byte stream to store it
in a file, database, or transmit it over a network.
● Deserialization: The process of reconstructing the object from the byte stream.
Key Features
● Provides persistence for objects.
● Facilitates communication between systems by transferring objects as byte
streams.
43
● Ensures state consistency when objects are passed between applications.
Classes and Interfaces for Serialization
● java.io.Serializable:
○ A marker interface (does not contain methods).
○ Any class implementing this interface is eligible for serialization.
● ObjectOutputStream:
○ Used to write objects to an output stream.
● ObjectInputStream:
○ Used to read objects from an input stream.
Serialization Example
Step 1: Define a Serializable Class
● Implement Serializable in the class.
● All fields of the class should be serializable (primitives and serializable objects).
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for
version control
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + ", salary=" +
salary + "}";
}
}
Step 2: Serialize the Object
● Use ObjectOutputStream to write the object to a file.
import java.io.FileOutputStream;
44
import java.io.ObjectOutputStream;
public class SerializeDemo {
public static void main(String[] args) {
Employee emp = new Employee("John Doe", 101, 50000.0);
try (FileOutputStream fos = new FileOutputStream("employee.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(emp); // Serialize the object
System.out.println("Object has been serialized.");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Step 3: Deserialize the Object
● Use ObjectInputStream to read the object from the file.
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeDemo {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("employee.ser");
ObjectInputStream ois = new ObjectInputStream(fis)) {
Employee emp = (Employee) ois.readObject(); // Deserialize the object
System.out.println("Object has been deserialized.");
System.out.println(emp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advantages
● Simplifies object persistence.
● Facilitates communication in distributed systems (e.g., RMI, sockets).
__________*____________*______________* _____________*_____________
45
S.
N Question a) Option b) Option c) Option d) Option
o
Which object
builds an
1 information block Skeleton Object Stub Object Server Object Client Object
and sends it to the
server?
Which object
passes the
Client
2 request from the Server Object Skeleton Object Remote Object
Object
Stub object to the
server?
Which tool is used
3 to invoke the RMI javac javadoc rmiregistry rmic
compiler?
When starting the
RMI registry
start rmiregistry
4 service, which java rmiregistry registry start
rmiregistry start
command should
be issued?
Which method is
createRegi
5 used to create an startRegistry newRegistry locateRegistry
stry
RMI registry?
Which method is
used to bind a
6 remote object to a register lookup rebind find
new name in the
RMI registry?
Which method is
used to get the
7 bind rebind register lookup
reference of the
Stub object?
Remote
What does RPC Random Related Process Relational
8 Procedure
stand for? Procedure Call Call Process Call
Call
Which type of
system consists of
a network of Client-Server Distributed Peer-to-Peer
9 Cloud System
independent System System System
computers that
work together?
Which component
1 provides services Both the client
The client The server The network
0 or resources to and the server
clients?
46
UNIT-3
3.1 JDBC Principles
3.2 Database Access
3.3 Database Search
3.4 Creating Multimedia Databases
3.5 Database Support in Web Applications
_______________________________________________________________________
3.1 JDBC Principles
Introduction to JDBC
● Java Database Connectivity (JDBC) is a Java API used for connecting to
relational databases, executing SQL statements, and retrieving results.
● JDBC acts as a bridge between a Java application and a database, enabling
interaction with various database systems.
JDBC Architecture
1. Application Layer:
○ Java application interacts with the database through the JDBC API.
2. JDBC API:
○ Defines interfaces and classes for database access.
○ Works with any database using specific drivers.
3. JDBC Driver Manager:
○ Manages the communication between the application and the database
driver.
4. Database:
○ The actual data storage system.
JDBC Drivers
JDBC supports four types of drivers:
1. Type 1: JDBC-ODBC Bridge Driver:
○ Connects to databases via ODBC.
○ Simple but requires ODBC installation.
2. Type 2: Native API Driver:
○ Converts JDBC calls to native database API.
○ Faster than Type 1 but platform-dependent.
3. Type 3: Network Protocol Driver:
○ Uses a middleware server to translate JDBC requests into database calls.
47
○ Platform-independent.
4. Type 4: Thin Driver:
○ Directly converts JDBC calls into database-specific protocol.
○ Most commonly used, fast, and platform-independent.
Key Components of JDBC
DriverManager
● Manages the JDBC drivers.
● Establishes connections to databases.
Connection
● Represents the session between the Java application and the database.
● Methods:
○ createStatement(): Creates a Statement object.
○ prepareStatement(String sql): Creates a PreparedStatement object.
Statement
● Used to execute SQL queries.
● Types:
○ Statement: For basic SQL queries.
○ PreparedStatement: Precompiled queries with placeholders.
○ CallableStatement: Executes stored procedures.
ResultSet
● Represents the result of a query.
● Provides methods to navigate and retrieve data:
○ next(): Moves to the next row.
○ getString(columnIndex), getInt(columnIndex): Retrieves data from
columns.
Steps to Connect to a Database Using JDBC
1. Load the Driver: Explicit loading is required for older JDBC versions.
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection: Use DriverManager to connect to the database.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");
3. Create a Statement: Use Statement, PreparedStatement, or CallableStatement.
Statement stmt = con.createStatement();
4. Execute Queries: Use executeQuery() for SELECT or executeUpdate() for
48
INSERT, UPDATE, DELETE.
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
5. Process Results: Use the ResultSet to fetch query results.
while (rs.next()) {
System.out.println("Name: " + rs.getString("name"));
}
6. Close Resources: Close the ResultSet, Statement, and Connection objects to
release resources.
rs.close();
stmt.close();
con.close();
Advanced Features
PreparedStatement : Prevents SQL injection by parameterizing queries.
Example:
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, 10);
ResultSet rs = ps.executeQuery();
CallableStatement - Executes stored procedures in the database.
Example:
CallableStatement cs = con.prepareCall("{call my_procedure(?, ?)}");
cs.setInt(1, 10);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
Batch Processing - Executes multiple queries in a single batch for efficiency.
Example:
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO employees VALUES (1, 'John')");
stmt.addBatch("INSERT INTO employees VALUES (2, 'Jane')");
stmt.executeBatch();
Transactions - Ensures data consistency using commit and rollback.
Example:
con.setAutoCommit(false);
stmt.executeUpdate("INSERT INTO employees VALUES (1, 'John')");
con.commit();
49
Advantages of JDBC
● Platform-independent API.
● Works with multiple database systems.
● Flexible and customizable query execution.
Limitations of JDBC
● Requires writing SQL queries manually.
● Debugging can be challenging for complex queries.
● High-level abstractions like ORM frameworks (e.g., Hibernate) are often
preferred for large applications.
52
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "password";
try (Connection con = DriverManager.getConnection(url, username, password)) {
String query = "SELECT * FROM employees WHERE department = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, "Sales");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Best Practices for Database Search
1. Use Indexing:
○ Ensure columns used in search conditions are indexed for faster
performance.
2. Validate Inputs:
○ Prevent injection attacks by validating user inputs.
3. Batch Results:
○ Use pagination for large datasets to avoid memory issues.
4. Optimize Queries:
○ Use explain plans to optimize query performance.
54
ps.setString(2, "image/png");
FileInputStream fis = new FileInputStream("path/to/image.png");
ps.setBinaryStream(3, fis);
ps.executeUpdate();
4. Retrieve Data: Retrieve and process multimedia files using JDBC or APIs.
Example:
ResultSet rs = stmt.executeQuery("SELECT data FROM multimedia WHERE id = 1");
if (rs.next()) {
InputStream is = rs.getBinaryStream("data");
FileOutputStream fos = new FileOutputStream("output.png");
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) fos.write(buffer);
}
Indexing and Searching Multimedia Data
● Use metadata for efficient indexing (e.g., tags, timestamps).
● Full-text search for associated text data (e.g., descriptions).
Example Query:
SELECT * FROM multimedia WHERE metadata->>'$.author' = 'John Doe';
Challenges in Multimedia Databases
● Large storage requirements.
● Complex indexing and searching.
● Performance issues with unoptimized queries.
Applications
● Digital Libraries.
● Online Media Streaming (e.g., YouTube, Spotify).
● Image and Video Storage Systems.
56
PreparedStatement ps = con.prepareStatement(insertQuery);
ps.setString(1, "jane_doe");
ps.setString(2, "hashed_password");
ps.executeUpdate();
57
● Scalability: Handling increased traffic.
● Consistency: Ensuring data accuracy during concurrent operations.
● Security: Protecting sensitive data.
S.
Question a) Option b) Option c) Option d) Option
No
What does Java Java
Java Database Java Data
1 JDBC stand Database Development
Compiler Connection
for? Connectivity Class
Which JDBC
driver
Native API JDBC-ODBC Database- Network Protocol
2 connects to
Driver Bridge Driver specific Driver Driver
databases via
ODBC?
Which of the
following
3 converts JDBC ODBC Driver Native API Driver JDBC Driver Protocol Driver
calls to native
database API?
Which of the
following
Create, Read, Create, Remove, Connect,
represents the Create, Retrieve,
4 Update, Upload, Read, Update,
four basic Undo, Delete
Delete Download Delete
CRUD
operations?
Which object
stores the
Connection ResultSet DriverManager
5 result of a Statement object
object object object
query in
JDBC?
Which
mechanism
executes
Batch Connection Transaction ResultSet
6 multiple
Processing Pooling Management Handling
queries in a
single batch
for efficiency?
Which
method is
used to DriverManage
ResultSet.getCo Connection.c Statement.execu
7 establish a r.getConnecti
nnection() onnect() teQuery()
connection to on()
a database in
JDBC?
8 Which executeUpdat executeQuery() execute() executedb()
method is e()
used to
execute
SELECT
queries in
58
JDBC?
Which of the
following is an
9 example of a MySQL PostgreSQL MongoDB Oracle Database
NoSQL
database?
Which type of
database is
ideal for
Relational Object-Oriented NoSQL
10 unstructured SQL Databases
Databases Databases Databases
or semi-
structured
data?
59
UNIT - IV
Faster (lightweight,
Performance Slower (higher resource usage)
shared JVM)
Platform Platform-independent
Language-dependent
Dependency (Java)
60
Steps to Create and Deploy a Servlet:
1. Setup Environment:
○ Install a servlet container (e.g., Apache Tomcat).
○ Configure Java Development Kit (JDK).
2. Write the Servlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
}
3. Compile the Servlet:
○ Compile using javac to generate the .class file.
4. Deploy to Web Server:
○ Place the .class file in the WEB-INF/classes directory.
○ Update the web.xml deployment descriptor (optional in modern servlet
containers).
xml
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
61
5. Access via Browser:
○ Run the server and access http://localhost:8080/appname/hello.
Servlet Lifecycle
1. Initialization:
○ init() method called once when the servlet is loaded.
2. Handling Requests:
○ service() method routes requests to doGet() or doPost().
3. Termination:
○ destroy() method called before unloading the servlet.
Advantages of Java Servlets
1. High performance due to thread-based processing.
2. Platform independence and extensive API support.
3. Easy integration with other Java EE components (e.g., JSP, EJB).
4. Enhanced security features and session management.
Method Purpose
63
2. HttpServletResponse:
○ Used to send the response back to the client.
○ Key Methods:
■ setContentType(String type) – Sets MIME type of the response.
■ getWriter() – Writes text responses.
3. ServletConfig:
○ Provides configuration information for the servlet.
4. ServletContext:
○ Shared among all servlets in the application for global information.
Example Structure of a Simple Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ExampleServlet extends HttpServlet {
@Override
public void init() throws ServletException {
// Initialization code
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Welcome to Servlets</h1>");
out.println("</body></html>");
}
@Override
public void destroy() {
// Cleanup code
}
}
Benefits of Servlets
1. Platform-independent and secure.
2. Thread-based, ensuring efficient use of resources.
3. Scalable, robust, and integrates well with Java EE components.
4. Enables session management and application-specific logic.
4.3 Reading data from a client - Reading http request header-sending data to a client
64
and writing the http response header
1. Reading Data from a Client
Data sent by a client can be read using the HttpServletRequest object provided by the
servlet container. Common methods include:
Reading Form Data
Form data sent via GET or POST can be retrieved using getParameter().
String name = request.getParameter("name");
String age = request.getParameter("age");
Reading Request Body
For POST data, the request body can be read using getReader().
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
Example Code:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Welcome, " + username + "</h1>");
}
2. Reading HTTP Request Headers
HTTP headers provide metadata about the request. They can be accessed using
HttpServletRequest methods:
Common Methods
1. String userAgent = request.getHeader("User-Agent");
2. Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println(headerName + ": " + headerValue);
65
}
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Enumeration<String> headers = request.getHeaderNames();
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
while (headers.hasMoreElements()) {
String headerName = headers.nextElement();
out.println(headerName + ": " + request.getHeader(headerName));
}
}
3. Sending Data to a Client
The HttpServletResponse object is used to send data to the client. Key methods
include:
Setting Content Type
Specifies the MIME type of the response.
response.setContentType("text/html");
Writing Response Data
Use getWriter() for text data and getOutputStream() for binary data.
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Dynamic Content</h1>");
out.println("<p>This page was generated using Java Servlets.</p>");
out.println("</body></html>");
}
66
4. Writing HTTP Response Headers
HTTP response headers provide metadata about the response. The
HttpServletResponse object offers methods to manipulate these headers:
Common Methods
1. setHeader(String name, String value)
○ Sets a response header.
response.setHeader("Cache-Control", "no-cache");
2. addHeader(String name, String value)
○ Adds a response header without overwriting existing values.
response.addHeader("Set-Cookie", "userId=12345");
3. setStatus(int statusCode)
○ Sets the HTTP status code.
response.setStatus(HttpServletResponse.SC_OK);
4. sendError(int statusCode, String message)
○ Sends an error response with a custom message.
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request data");
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Custom-Header", "MyValue");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>HTTP Headers Example</h1>");
out.println("</body></html>");
}
68
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
String username = cookie.getValue();
System.out.println("Username: " + username);
}
}
}
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (cookies != null) {
for (Cookie cookie : cookies) {
out.println("<p>Cookie Name: " + cookie.getName() + "</p>");
out.println("<p>Cookie Value: " + cookie.getValue() + "</p>");
}
} else {
out.println("<h1>No Cookies Found</h1>");
}
}
Deleting Cookies
To delete a cookie, set its maximum age to 0 and add it to the response.
Steps to Delete a Cookie:
1. Retrieve the existing cookie.
2. Set its MaxAge to 0.
3. Add it back to the response.
Example Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
69
if (cookie.getName().equals("username")) {
cookie.setMaxAge(0); // Delete the cookie
response.addCookie(cookie);
} } }
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Cookie Deleted Successfully</h1>");
}
71
http://localhost:8080/hello.jsp
Step 4: Configure Environment (Optional)
● Configure additional settings in conf/server.xml or deploy specific web
applications in the webapps folder.
72
Declare variables or methods for use throughout the page.
Example:
<%! int counter = 0; %>
<%! public String greet() { return "Hello!"; } %>
ii) Scriptlets (<% ... %>)
Embed blocks of Java code.
Example:
<%
String user = "John";
out.println("Welcome, " + user);
%>
iii) Expressions (<%= ... %>)
Outputs the result of a Java expression directly to the page.
Example:
<p>The current time is: <%= new java.util.Date() %></p>
3. Action Elements
Action elements perform predefined actions and interact with server-side components.
i) <jsp:include>: Dynamically includes another resource.
Example:
<jsp:include page="footer.jsp" />
ii) <jsp:forward>: Forwards the request to another resource.
Example:
<jsp:forward page="nextPage.jsp" />
iii) <jsp:useBean>: Instantiates or references a JavaBean.
Example:
<jsp:useBean id="user" class="com.example.User" />
iv) <jsp:setProperty> and <jsp:getProperty>:
Sets and retrieves properties of JavaBeans.
Example:
<jsp:setProperty name="user" property="name" value="Alice" />
<jsp:getProperty name="user" property="name" />
4. Implicit Objects
JSP provides pre-defined objects that are available in every JSP page without explicit
declaration.
73
Common Implicit Objects:
● request: Represents the HTTP request and contains client data.
● response: Represents the HTTP response sent to the client.
● session: Represents the session object for the client.
● out: Used to send content to the client.
● application: Represents the ServletContext shared by all servlets and JSPs.
● config: Provides servlet configuration data.
● pageContext: Facilitates interaction between JSP components.
● exception: Represents exceptions, available in error pages.
5. Static Content
JSP pages can include HTML, CSS, JavaScript, and other static content alongside
dynamic Java code.
Example of Static Content:
<head>
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome to the Website</h1>
</body>
</html>
6. Custom Tags and Tag Libraries
Custom tags and tag libraries allow the reuse of functionality and simplify the JSP code.
Taglib Example:
jsp
Copy code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:if test="${user != null}">
<p>Welcome, ${user.name}</p>
</c:if>
A Complete JSP Page
Here’s an example of a complete JSP page with all components:
<%@ page language="java" contentType="text/html" %>
<%@ include file="header.jsp" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
74
<html>
<head>
<title>My JSP Page</title>
</head>
<body>
<%
String name = "Alice";
int visits = 5;
%>
<h1>Welcome, <%= name %>!</h1>
<p>This is your <%= visits %> visit.</p>
<c:if test="${visits > 1}">
<p>We’re glad to see you again!</p>
</c:if>
<jsp:include page="footer.jsp" />
</body>
</html>
76
S.
N Question a) Option b) Option c) Option d) Option
o
Which of the following
1 methods in a servlet is used to doPost() service() doGet() init()
handle GET requests?
What is the purpose of the init() Dispatches Handles POST Initializes Cleans up
2
method in a servlet? requests requests the servlet resources
Which method is used to clean
getServletC
3 up resources before a servlet destroy() doGet() service()
onfig()
is unloaded?
Which method retrieves the
getServletCo
4 configuration details of a getServ() service() destroy()
nfig()
servlet?
Which of the following is a Apache Apache
5 Apache Kafka Java Cat
servlet container? Tomcat Java
Which method handles
6 init() destroy() service() doGet()
requests in a servlet?
Which directive in JSP declares Taglib Include UseBean
7 Page Directive
a library of custom tags? Directive Directive Directive
Which JSP tag is used to
<jsp:useBe <jsp:scriptl
8 forward a request to another <jsp:include> jsp:forward
an> et>
resource?
Which JSP tag is used to
jsp:useBea <jsp:forwar <jsp:scriptl
9 instantiate or reference a <jsp:include>
n d> et>
JavaBean?
Which of the following JSP tags
1 <jsp:useBe <jsp:scriptl
dynamically includes another <jsp:forward> jsp:include
0 an> et>
resource?
77
UNIT - V
78
javac HelloWorld.java
ii) Create the JAR File:
Use the jar command to bundle the compiled files.
Example:
bash
jar cf HelloWorld.jar HelloWorld.class
iii) Verify the JAR File:
Use the jar command to view the contents of the JAR file.
Example:
bash
jar tf HelloWorld.jar
4. Adding a Manifest File
A manifest file (META-INF/MANIFEST.MF) provides metadata about the JAR file, such as
the main class for execution.
Example Manifest File (manifest.txt):
plaintext
Manifest-Version: 1.0
Main-Class: HelloWorld
Create a JAR File with a Manifest:
bash
jar cfm HelloWorld.jar manifest.txt HelloWorld.class
● m: Include a manifest file.
Run the JAR File:
If the Main-Class is specified in the manifest, you can run the JAR file directly:
bash
java -jar HelloWorld.jar
5. Adding Multiple Files and Directories
You can include multiple files and directories in a JAR file. For example:
bash
jar cf MyApp.jar *.class images/ config/
This command packages all .class files, the images directory, and the config directory
into MyApp.jar.
6. Updating an Existing JAR File
To add new files to an existing JAR, use the u option:
79
bash
jar uf HelloWorld.jar NewClass.class
7. Extracting Files from a JAR File
To extract files from a JAR, use the x option:
bash
jar xf HelloWorld.jar
8. Signing a JAR File
To ensure the integrity of the JAR file, you can sign it using the jarsigner tool:
bash
jarsigner -keystore myKeystore -signedjar SignedHelloWorld.jar HelloWorld.jar myAlias
9. Example Workflow
Source Code (HelloWorld.java):
java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compile the Code:
javac HelloWorld.java
Create a Manifest (manifest.txt):
Manifest-Version: 1.0
Main-Class: HelloWorld
Create the JAR File:
jar cfm HelloWorld.jar manifest.txt HelloWorld.class
Run the JAR File:
java -jar HelloWorld.jar
81
ResourceBundle bundle = ResourceBundle.getBundle("Messages", locale);
System.out.println(bundle.getString("greeting")); // Output: Bonjour
System.out.println(bundle.getString("farewell")); // Output: Au revoir
}
}
83
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
4. Event Handling in Swing
Swing uses an event-driven model, meaning that an application responds to events
(like mouse clicks, key presses, etc.) generated by user actions.
● Event Sources: Objects that generate events (e.g., buttons, text fields).
● Event Listeners: Objects that handle events (e.g., ActionListener,
MouseListener).
Example (Button Click Listener):
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonClickExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button clicked!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
84
In this example, when the button is clicked, a message dialog is shown using
JOptionPane.
85
6. Advanced Features in Swing
Look and Feel (L&F): Swing supports different look and feels, allowing you to customize
the appearance of the GUI. The default look and feel is "Metal," but other L&F like
"Windows" and "Motif" can be applied.
Example:
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
● JProgressBar: Used to show the progress of a task.
● JTabbedPane: Allows the creation of tabbed panes for organizing content into
separate tabs.
● JToolBar: A panel with buttons or controls that provide quick access to
frequently used operations.
Concurrency in Java refers to the ability to execute multiple tasks at the same time.
Java provides built-in support for multithreading, allowing developers to take full
advantage of multi-core processors.
Thread Basics
86
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
Thread Lifecycle
Synchronization
Synchronized methods:
Synchronized blocks:
synchronized(this) {
// thread-safe block of code
}
Executor Framework
87
Singleton Pattern
Ensures that a class has only one instance and provides a global point of access.
Example:
Factory Pattern
Defines an interface for creating objects, but lets subclasses decide which class to
instantiate.
Example:
interface Product {
void doSomething();
}
class ConcreteProductA implements Product {
public void doSomething() {
System.out.println("Product A");
}
}
class ProductFactory {
public Product createProduct(String type) {
if (type.equals("A")) {
return new ConcreteProductA();
}
// return other products
return null;
}
}
Lambda Expressions
Syntax:
88
(parameters) -> expression
Example:
(a, b) -> a + b
Streams API
Example:
Functional Interfaces
Functional interfaces have a single abstract method and may contain default or static
methods.
Example:
@FunctionalInterface
interface MyInterface {
void myMethod();
}
Java Reflection
Example:
Garbage Collection
-------------------------------------------------------------------------------
89
S. c) d)
Question a) Option b) Option
No Option Option
Java
Java Accessibl
What does JAR stand for in Java Access Java
1 Application e
Java? Resource Archive
Runtime Repositor
y
What type of file is a JAR file Executabl
2 Text file ZIP file Audio file
essentially? e file
Which file contains metadata Resource
3 Class file Manifest file ZIP file
about the JAR file? file
Which command is used to
4 compile .java files into java javac jar javadoc
bytecode?
Which object represents a
Resource Event
5 specific geographical, Locale JFrame
bundle listener
political, or cultural region?
To
To store compile To display
What are resource bundles To store Java
6 locale-specific Java error
used for in Java? bytecode
objects source messages
code
Which of the following is used
7 for building graphical user JDBC Swing JAR Threads
interfaces (GUIs)?
Identify the component used
8 to represent the main window JDialog JFrame JList JTextField
of the application.
Identify the Swing component
JProgressBa
9 used to create a pop-up dialog JDialog JTextField JWindow
r
box.
Identify the component used
JPasswor
10 to enter text as a single line of JTextArea JTextField JLabel
dField
input.
90