0% found this document useful (0 votes)
2 views31 pages

Java

The document provides an overview of event handling in Java, explaining the classification of events into foreground and background, and detailing the event handling mechanism using the Delegation Event Model with sources and listeners. It also covers the lifecycle of threads in Java, multithreading concepts, and Java networking, including socket programming and the use of the java.net package for communication between devices. Key components such as event classes, listener interfaces, and thread priorities are discussed, along with examples of creating and managing threads.

Uploaded by

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

Java

The document provides an overview of event handling in Java, explaining the classification of events into foreground and background, and detailing the event handling mechanism using the Delegation Event Model with sources and listeners. It also covers the lifecycle of threads in Java, multithreading concepts, and Java networking, including socket programming and the use of the java.net package for communication between devices. Key components such as event classes, listener interfaces, and thread priorities are discussed, along with examples of creating and managing threads.

Uploaded by

pramilaalagar2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Event Handling in Java

An event is a change in the state of an object triggered by


some action such as Clicking a button, Moving the cursor,
Pressing a key on the keyboard, Scrolling a page, etc. In Java,
the [Link] package provides various event classes to

handle these actions.


Classification of Events
Events in Java can be broadly classified into two categories
based on how they are generated:
1. Foreground Events: Foreground events are the events
that require user interaction to generate. Examples of
these events include Button clicks, Scrolling the
scrollbar, Moving the cursor, etc.
2. Background Events: Events that don't require
interactions of users to generate are known as
background events. Examples of these events are
operating system failures/interrupts, operation
completion, etc.
Event Handling Mechanism
Event handling is a mechanism that allows programs to control
events and define what should happen when an event occurs.
Java uses the Delegation Event Model to handle events. This
model consists of two main components:
 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.

Registering the Source With Listener


To handle events, the source must be registered with a listener.
Java provides specific methods for registering listeners based on
the type of event.
Syntax:
addTypeListener()
For example,
 addKeyListener() for KeyEvent
 addActionListener() for ActionEvent

Event Classes and Listener Interfaces


Java provides a variety of event classes and corresponding
listener interfaces. Below table demonstrates the most
commonly used event classes and their associated listener
interfaces:

Listener
Event Class Interface Description

ActionEvent ActionListener An event that indicates


that a component-
defined action occurred
like a button click or
Listener
Event Class Interface Description

selecting an item from


the menu-item list.

The adjustment event is


AdjustmentEvent AdjustmentListener emitted by an Adjustable
object like Scrollbar.

An event that indicates


that a component
ComponentEvent ComponentListener
moved, the size changed
or changed its visibility.

When a component is
added to a container (or)
ContainerEvent ContainerListener removed from it, then
this event is generated
by a container object.

These are focus-related


events, which include
FocusEvent FocusListener
focus, focusin, focusout,
and blur.

An event that indicates


ItemEvent ItemListener whether an item was
selected or not.

An event that occurs


due to a sequence of
KeyEvent KeyListener
keypresses on the
keyboard.

MouseEvent MouseListener & The events that occur


MouseMotionListener due to the user
interaction with the
Listener
Event Class Interface Description

mouse (Pointing Device).

An event that specifies


MouseWheelEve that the mouse wheel
MouseWheelListener
nt was rotated in a
component.

An event that occurs


TextEvent TextListener when an object's text
changes.

An event which indicates


whether a window has
WindowEvent WindowListener
changed its status or
not.

Note: As Interfaces contains abstract methods which need to


implemented by the registered class to handle events.
Methods in Listener Interfaces
Each listener interface contains specific methods that must be
implemented to handle events. Below table demonstrates the
key methods for each interface:

Listener Interface Methods

ActionListener actionPerformed()

adjustmentValueChange
AdjustmentListener
d()

ComponentListener componentResized()
componentShown()
componentMoved()
Listener Interface Methods

componentHidden()

componentAdded()
ContainerListener
componentRemoved()

focusGained()
FocusListener
focusLost()

ItemListener itemStateChanged()

keyTyped()
KeyListener keyPressed()
keyReleased()

mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()

mouseMoved()
MouseMotionListener
mouseDragged()

MouseWheelListener mouseWheelMoved()

TextListener textChanged()

WindowListener windowActivated()
windowDeactivated()
Listener Interface Methods

windowOpened()
windowClosed()
windowClosing()
windowIconified()
windowDeiconified()

Flow of Event Handling


The event handling process in Java follows these steps:
1. User Interaction with a component is required to
generate an event.
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.

Steps to perform Event Handling


• Following steps are required to perform event handling:
1. Register the component with the Listener Registration
Methods
2. • For registering the component with the Listener, many
classes provide the registration methods.
3. For example:
4. • Button
5. • public void addActionListener(ActionListener a){}
6. • MenuItem
7. • public void addActionListener(ActionListener a){}
8. • TextField
9. • public void addActionListener(ActionListener a){}
10. • public void addTextListener(TextListener a){}
11. • TextArea
12. • public void addTextListener(TextListener a){}
13. • Checkbox
14. • public void addItemListener(ItemListener a){}
15. • Choice
16. • public void addItemListener(ItemListener a){}
17. • List
18. • public void addActionListener(ActionListener a){}
19. • public void addItemListener(ItemListener a){}
What is a Thread in Java?

A thread in Java is the direction or path that is taken while a program is


being executed. Generally, all the programs have at least one thread,
known as the main thread, that is provided by the JVM or Java Virtual
Machine at the starting of the program’s execution. At this point, when
the main thread is provided, the main() method is invoked by the main
thread.

A thread is an execution thread in a program. Multiple threads of


execution can be run concurrently by an application running on the Java
Virtual Machine. The priority of each thread varies. Higher priority threads
are executed before lower priority threads.

Thread is critical in the program because it enables multiple operations to


take place within a single method. Each thread in the program often has
its own program counter, stack, and local variable.

Thread in Java enables concurrent execution, dividing tasks for improved


performance. It's essential for handling operations like I/O and network
communication efficiently. Understanding threads is crucial for responsive
Java applications. Enroll in a Java Course to master threading and create
efficient multithreaded programs.

Creating a Thread
There are two ways to create a thread.

It can be created by extending the Thread class and overriding


its run() method:

Extend Syntax
public class Main extends Thread {

public void run() {

[Link]("This code is running in a thread");

Another way to create a thread is to implement the Runnable interface:

Implement Syntax
public class Main implements Runnable {

public void run() {

[Link]("This code is running in a thread");

}
}

Running Threads
If the class extends the Thread class, the thread can be run by creating an
instance of the class and call its start() method:

Extend Example
public class Main extends Thread {

public static void main(String[] args) {

Main thread = new Main();

[Link]();

[Link]("This code is outside of the thread");

public void run() {

[Link]("This code is running in a thread");

Lifecycle of a Thread in Java

The Life Cycle of a Thread in Java refers to the state transformations of a


thread that begins with its birth and ends with its death. When a thread
instance is generated and executed by calling the start() method of the
Thread class, the thread enters the runnable state. When the sleep() or
wait() methods of the Thread class are called, the thread enters a non-
runnable mode.
Thread returns from non-runnable state to runnable state and starts
statement execution. The thread dies when it exits the run() process.
In Java, these thread state transformations are referred to as the Thread
life cycle.

There are basically 4 stages in the lifecycle of a thread, as given below:

1. New

2. Runnable

3. Running

4. Blocked (Non-runnable state)

5. Dead
 New State

As we use the Thread class to construct a thread entity, the thread is born
and is defined as being in the New state. That is, when a thread is
created, it enters a new state, but the start() method on the instance has
not yet been invoked.

 Runnable State

A thread in the runnable state is prepared to execute the code. When a


new thread's start() function is called, it enters a runnable state.

In the runnable environment, the thread is ready for execution and is


awaiting the processor's availability (CPU time). That is, the thread has
entered the queue (line) of threads waiting for execution.

 Running State

Running implies that the processor (CPU) has assigned a time slot to the
thread for execution. When a thread from the runnable state is chosen for
execution by the thread scheduler, it joins the running state.

In the running state, the processor allots time to the thread for execution
and runs its run procedure. This is the state in which the thread directly
executes its operations. Only from the runnable state will a thread enter
the running state.

 Blocked State

When the thread is alive, i.e., the thread class object persists, but it
cannot be selected for execution by the scheduler. It is now inactive.
 Dead State

When a thread's run() function ends the execution of sentences, it


automatically dies or enters the dead state. That is, when a thread exits
the run() process, it is terminated or killed. When the stop() function is
invoked, a thread will also go dead.

Java Thread Priorities

The number of services assigned to a given thread is referred to as its


priority. Any thread generated in the JVM is given a priority. The priority
scale runs from 1 to 10.

1 is known as the lowest priority.

5 is known as standard priority.

10 represents the highest level of priority.

The main thread's priority is set to 5 by default, and each child thread will
have the same priority as its parent thread. We have the ability to adjust
the priority of any thread, whether it is the main thread or a user-defined
thread. It is advised to adjust the priority using the Thread class's
constants, which are as follows:

1. Thread.MIN_PRIORITY;

2. Thread.NORM_PRIORITY;

3. Thread.MAX_PRIORITY;
Most Commonly Used Constructors in Thread Class

The Thread class includes constructors and methods for creating and
operating on threads. Thread extends Object and implements the
Runnable interface.

 Thread()

The default Thread() constructor is used to create a new Thread class.

 Thread (String str)

A thread object is created and a name is provided to the same.

 Thread (Runnable r)

In this constructor type, Runnable reference is passed and a new Thread


object is created.

 Thread (Runnable r, String r)

We may use this constructor to generate a new Thread object by passing


a Runnable reference as the first parameter and also providing a name for
the newly generated thread

Multithreading in Java

In Java, multithreading is the method of running two or more threads at


the same time to maximize CPU utilization. As a result, it is often referred
to as Concurrency in Java. Each thread runs in parallel with the others.
Since several threads do not assign different memory areas, they
conserve memory. Furthermore, switching between threads takes less
time.
In Java, multithreading enhances program structure by making it simpler
and easier to navigate. These generalized threads can be used in high-
server media applications to easily change or enhance the configuration
of these complex structures.

class MyThread extends Thread {

public void run() {

[Link]("Thread started");

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

[Link]("Number: " + i);

[Link]("Thread finished");

public static void main(String[] args) {

MyThread t1 = new MyThread();

// NEW

[Link]("State after creation: " + [Link]());

// RUNNABLE

[Link]();

[Link]("State after start: " + [Link]());

try {

[Link](); // wait for thread to complete


} catch (Exception e) {

[Link](e);

// TERMINATED

[Link]("State after completion: " + [Link]());

State after creation: NEW

State after start: RUNNABLE

Thread started

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

Thread finished

State after completion: TERMINATED

java Networking
Java networking (or, Java network programming) refers to writing
programs that execute across multiple devices (computers), in 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 [Link] 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 [Link] package provides support for the two common network
protocols −

 TCP − TCP stands for Transmission Control Protocol, which allows for
reliable 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 connection-less
protocol that allows for packets of data to be transmitted between
applications.

This chapter gives a good understanding on the following two subjects −

 Socket Programming − This is the most widely used concept in


Networking and it has been explained in very detail.
 URL Processing − This would be covered separately. Click here to
learn about URL Processing in Java language.

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 [Link] class represents a socket, and the


[Link] 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
complete set of methods to implement sockets.

ServerSocket Class Constructors


The [Link] class is used by server applications to obtain a
port and listen for client requests.

The ServerSocket class has four constructors −

[Link]
Method & Description
.

public ServerSocket(int port) throws IOException


1 Attempts to create a server socket bound to the specified port. An
exception occurs if the port is already bound by another application.

public ServerSocket(int port, int backlog) throws IOException


2 Similar to the previous constructor, the backlog parameter specifies how
many incoming clients to store in a wait queue.

public ServerSocket(int port, int backlog, InetAddress address)


throws IOException
3
Similar to the previous constructor, the InetAddress parameter specifies
the local IP address to bind to. The InetAddress is used for servers that
may have multiple IP addresses, allowing the server to specify which of its
IP addresses to accept client requests on.

public ServerSocket() throws IOException


4 Creates an unbound server socket. When using this constructor, use the
bind() method when you are ready to bind the server socket.
If the ServerSocket constructor does not throw an exception, it means that
your application has successfully bound to the specified port and is ready for
client requests.

ServerSocket Class Methods

Following are some of the common methods of the ServerSocket class −

[Link]
Method & Description
.

public int getLocalPort()


1 Returns the port that the server socket is listening on. This method is useful if you
passed in 0 as the port number in a constructor and let the server find a port for you.

public Socket accept() throws IOException


Waits for an incoming client. This method blocks until either a client connects to the
2 server on the specified port or the socket times out, assuming that the time-out value
has been set using the setSoTimeout() method. Otherwise, this method blocks
indefinitely.

public void setSoTimeout(int timeout)


3 Sets the time-out value for how long the server socket waits for a client during the
accept().

public void bind(SocketAddress host, int backlog)


4 Binds the socket to the specified server and port in the SocketAddress object. Use this
method if you have instantiated the ServerSocket using the no-argument constructor.

When the ServerSocket invokes accept(), the method does not return until a
client connects. After a client does connect, the ServerSocket creates a new
Socket on an unspecified port and returns a reference to this new Socket. A
TCP connection now exists between the client and the server, and
communication can begin.

Socket Class Constructors


The [Link] class represents the socket that both the client and the
server use to communicate with each other. The client obtains a Socket
object by instantiating one, whereas the server obtains a Socket object from
the return value of the accept() method.

The Socket class has five constructors that a client uses to connect to a
server −
[Link]
Method & Description
.

public Socket(String host, int port) throws UnknownHostException, IOException.


This method attempts to connect to the specified server at the specified port. If this
1
constructor does not throw an exception, the connection is successful and the client is
connected to the server.

public Socket(InetAddress host, int port) throws IOException


2 This method is identical to the previous constructor, except that the host is denoted by
an InetAddress object.

public Socket(String host, int port, InetAddress localAddress, int localPort)


throws IOException.
3
Connects to the specified host and port, creating a socket on the local host at the
specified address and port.

public Socket(InetAddress host, int port, InetAddress localAddress, int localPort)


throws IOException.
4
This method is identical to the previous constructor, except that the host is denoted by
an InetAddress object instead of a String.

public Socket()
5 Creates an unconnected socket. Use the connect() method to connect this socket to a
server.

When the Socket constructor returns, it does not simply instantiate a Socket
object but it actually attempts to connect to the specified server and port.

Socket Class Methods

Some methods of interest in the Socket class are listed here. Notice that both
the client and the server have a Socket object, so these methods can be
invoked by both the client and the server.

[Link]
Method & Description
.

public void connect(SocketAddress host, int timeout) throws IOException


1 This method connects the socket to the specified host. This method is needed only
when you instantiate the Socket using the no-argument constructor.
public InetAddress getInetAddress()
2
This method returns the address of the other computer that this socket is connected to.

public int getPort()


3
Returns the port the socket is bound to on the remote machine.

public int getLocalPort()


4
Returns the port the socket is bound to on the local machine.

public SocketAddress getRemoteSocketAddress()


5
Returns the address of the remote socket.

public InputStream getInputStream() throws IOException


6 Returns the input stream of the socket. The input stream is connected to the output
stream of the remote socket.

public OutputStream getOutputStream() throws IOException


7 Returns the output stream of the socket. The output stream is connected to the input
stream of the remote socket.

public void close() throws IOException


8 Closes the socket, which makes this Socket object no longer capable of connecting
again to any server.

InetAddress Class Methods

This class represents an Internet Protocol (IP) address. Here are following
usefull methods which you would need while doing socket programming −

[Link]. Method & Description

static InetAddress getByAddress(byte[] addr)


1
Returns an InetAddress object given the raw IP address.

static InetAddress getByAddress(String host, byte[] addr)


2
Creates an InetAddress based on the provided host name and IP address.

static InetAddress getByName(String host)


3
Determines the IP address of a host, given the host's name.
String getHostAddress()
4
Returns the IP address string in textual presentation.

String getHostName()
5
Gets the host name for this IP address.

static InetAddress InetAddress getLocalHost()


6
Returns the local host.

String toString()
7
Converts this IP address to a String.

Example of Java Networking


Implementing Socket Client in Java

The following GreetingClient is a client program that connects to a server by


using a socket and sends a greeting, and then waits for a response.

import [Link].*;
import [Link].*;

public class GreetingClient {


public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], [Link](args[1]));

DataOutputStream out = new DataOutputStream([Link]());


DataInputStream in = new DataInputStream([Link]());

[Link]("Hello from " + [Link]());


[Link]("Server says " + [Link]());

[Link]();
}
}

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

import [Link].*;
import [Link].*;

public class GreetingServer {


public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket([Link](args[0]));
[Link](10000);

while (true) {
try {
Socket s = [Link]();

DataInputStream in = new DataInputStream([Link]());


DataOutputStream out = new DataOutputStream([Link]());

[Link]([Link]());
[Link]("Thank you for connecting to " + [Link]() + "\
nGoodbye!");

[Link]();
} catch (SocketTimeoutException e) {
[Link]("Socket timed out!");
break;
}
}
}
}
OUTPUT:
(Server Side)
Hello from /[Link]:54321

(Client Side)
Server says Thank you for connecting to /[Link]:6066
Goodbye!

(Server Side after 10 sec)


Socket timed out!

Introduction Java Media Techniques


refer to the methods and APIs provided by Java to handle multimedia content such as
audio, video, images, animation, and streaming media . Java supports platform-independent
multimedia programming, allowing developers to create rich, interactive applications like
media players, educational software, games, and web-based multimedia applications.
in GUI applications

1. Java Media Framework (JMF)


The JMF manages time-based media (audio/video) through a specialized life cycle.
It uses DataSources to capture media and Players to render it. A key concept is
the State Model—a player must transition through Realizing (resource allocation)
and Prefetching (buffering) states before it can reach the Started state for playback.

2. JavaFX Media API


Modern media handling is done via JavaFX, which is more efficient than JMF. It
relies on three core components:

 Media: The resource (file or URL) and its metadata.


 MediaPlayer: The engine controlling playback (play, pause, seek).
 MediaView: The visual node that renders the video within the application's
scene graph.
3. Graphics and Imaging
Advanced visual techniques move beyond basic drawing to hardware-accelerated
processing:

 Java 2D & 3D: Used for complex geometry and 3D environment rendering.
 Java Advanced Imaging (JAI): Specialized for high-level image manipulation
like tiling, large-scale image processing, and complex filtering.
 Double Buffering: A technique where images are drawn to an off-screen
buffer before being shown, preventing "flickering" during animations.
4. Audio and Speech
 Java Sound API: Provides low-level control over audio hardware, supporting
both digital audio (PCM) and MIDI (Musical Instrument Digital Interface).
 Java Speech API (JSAPI): Enables Speech Synthesis (Text-to-Speech)
and Speech Recognition, allowing for voice-controlled interfaces.
5. Network Streaming (RTP)
For live media, Java uses the Real-time Transport Protocol (RTP). This allows for
transmitting and receiving synchronized audio and video over a network, critical for
conferencing and live broadcast applications.

High-Performance Graphics (Java 2D & 3D)


 Graphics2D Features: Advanced rendering in Java 2D includes Alpha
Compositing for transparency, Antialiasing for smooth edges,
and Geometric Transformations (scaling, rotation, and shearing).
 Complex Fills: Beyond solid colours, you can use GradientPaint for colour
interpolation and TexturePaint to fill shapes with repeated image fragments.
 Hardware Acceleration: For intensive 3D tasks, the Java Binding for the
OpenGL API (JOGL) provides full access to OpenGL 2.0 capabilities directly
from Java.
3. Advanced Animation & Interaction
 Double Buffering with BufferStrategy: To eliminate flickering, developers
use a BufferStrategy to manage multiple off-screen buffers (page flipping),
ensuring only complete frames are shown.
 Sprite Animation: Efficient animation is handled by loading Sprite
Sheets into a BufferedImage . You calculate the current frame's position
using the modulus operator to cycle through rows and columns of an image.
 Collision Detection: Advanced 2D graphics utilize hit detection on arbitrary
geometric shapes to manage interactions in games or CAD applications.
4. Specialized Imaging (JAI)
The Java Advanced Imaging (JAI) API is designed for heavy-duty image processing.

 Deferred Execution: Operations are only calculated when the results are
actually needed, saving memory.
 Large Data Handling: Supports image tiling and "Regions of Interest" (ROI),
allowing you to process massive images (like satellite photos) in smaller,
manageable chunks.
5. Java Sound and MIDI
 MIDI Synthesis: Java can act as a musical instrument,
controlling MIDI devices to play synthesized music rather than recorded audio
files.
 Capture and Transcoding: Advanced audio apps use JMF to capture live
audio from microphones and transcode it into formats like MP3 for storage or
streaming.

Remote Method Invocation in Java


Remote Method Invocation (RMI) in Java is an API that enables an
object in one JVM to invoke methods on an object located in
another JVM, either on the same machine or a remote system. It
supports building distributed applications by allowing seamless
client-server communication through method calls.
Uses a client-server architecture where the client invokes
methods on remote objects.
 Relies on the [Link] package and requires remote
interfaces extending Remote.
 Communication is managed internally by the JVM,
simplifying remote interaction.
Stub (Client-side Proxy): It acts as a proxy for the remote
object and forwards method calls from the client 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

Architecture of an RMI Application


In an RMI application, we write two programs, a server program (resides on
the server) and a client program (resides on the client).
 Inside the server program, a remote object is created and reference of
that object is made available for the client (using the registry).
 The client program requests the remote objects on the server and tries
to invoke its methods.

The following diagram shows the architecture of an RMI application.

Let us now discuss the components of this architecture.

 Transport Layer − This layer connects the client and the server. It
manages the existing connection and also sets up new connections.
 Stub − A stub is a representation (proxy) of the remote object at
client. It resides in the client system; it acts as a gateway for the client
program.
 Skeleton − This is the object which resides on the server
side. stub communicates with this skeleton to pass request to the
remote object.
 RRL(Remote Reference Layer) − It is the layer which manages the
references made by the client to the remote object.
Working of RMI
Communication between client and server is handled using a
Stub (client-side proxy), while server-side request handling is
managed internally by the RMI runtime.

The steps to implement RMI are as follows


The following steps demonstrate how to build and run a basic
RMI application in Java.

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.
import [Link];
import [Link]; // Creating Remote interface for
our application
public interface Hello extends Remote {
void printMsg() throws RemoteException;
}
tep 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 [Link] package. Also, a default
constructor needs to be created to throw the
[Link] from its parent constructor in class.

Developing the Implementation Class (Remote Object)

We need to implement the remote interface created in the earlier step. (We
can write an implementation class separately or we can directly make the
server program implement this interface.)

To develop an implementation class −

 Implement the interface created in the previous step.


 Provide implementation to all the abstract methods of the remote
interface.
Following is an implementation class. Here, we have created a class
named ImplExample and implemented the interface Hello created in the
previous step and provided body for this method which prints a message.
// Implementing the remote interface
public class ImplExample implements Hello {

// Implementing the interface method


public void printMsg() {
[Link]("This is an example RMI program");
}
}

step 3: No need to generate Stub/Skeleton manually


In modern Java, stub classes are generated dynamically by the
JVM, so the rmic tool is not required.
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.

import [Link];
import [Link];
import [Link];
import [Link];

public class Server extends ImplExample {


public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();
// Exporting the object of implementation class // (here we are
exporting the remote object to the stub)
Hello stub = (Hello)
[Link](obj, 0);
// Binding the remote object (stub) in the registry Registry
registry = [Link]();
[Link]("Hello", stub);
[Link]("Server ready");
} catch (Exception e) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}

step 6: Create and execute the client application program


The last step is to create the client application program and
execute it on a separate command prompt . The lookup method
of the Naming class is used to get the reference of the Stub
object.
import [Link];
import [Link];
public class Client {
private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = [Link](null);
// Looking up the registry for the remote object
Hello stub = (Hello) [Link]("Hello");
// Calling the remote method using the obtained object
[Link]();
// [Link]("Remote method invoked");
} catch (Exception e) {
[Link]("Client exception: " + [Link]());
[Link]();
}
}
}

Note: The above client and server program is executed on the


same machine so localhost is used. In order to access the
remote object from another machine, localhost is to be replaced
with the IP address where the remote object is present.
save the files respectively as per class name as
[Link] , [Link] , [Link] &
[Link]

Important Observations:
1. RMI is a pure java solution to Remote Procedure Calls
(RPC) and is used to create the distributed applications in
java.
2. Stub objects are used on the client side, while server-
side communication is handled internally by the RMI
runtime.

You might also like