0% found this document useful (0 votes)
23 views23 pages

JDBC Unit3

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

JDBC Unit3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 23

JDBC – UNIT-III

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database.

The java.sql package contains classes and interfaces for JDBC API. A list of
popular interfaces of JDBC API are given below:

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

JDBC Implementation
JDBC (Java Database Connectivity) is a Java API that enables Java programs to
interact with databases. It provides a standard interface for accessing relational
databases from Java programs..

Import JDBC Packages: You need to import the necessary JDBC packages. These typically include
java.sql and the database-specific JDBC driver packages.

import java.sql.*;

Load the JDBC Driver: Load the JDBC driver for your particular database. This involves using
Class.forName() with the appropriate driver class name. Different databases have different driver
class names.

Class.forName("com.mysql.cj.jdbc.Driver");
Establish a Connection: Connect to the database using DriverManager.getConnection(). You need
to provide the database URL, username, and password.

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",


"username", "password");

Create a Statement: Create a Statement object using the createStatement() method of the
Connection object. This statement object is used to execute SQL queries.

Statement statement = connection.createStatement();

Execute SQL Queries: You can execute SQL queries using the executeQuery() method for SELECT
queries or executeUpdate() for INSERT, UPDATE, DELETE queries.

ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table");

Process the Results: If you executed a SELECT query, you can iterate over the ResultSet object to
retrieve the results.

while (resultSet.next()) {

// Process each row of the result set

Close the Connection: Finally, close the ResultSet, Statement, and Connection objects to release
database resources.

resultSet.close();

statement.close();

connection.close();

Program:

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish a connection to the database


connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");

// Create a statement object


statement = connection.createStatement();

// Execute a query
resultSet = statement.executeQuery("SELECT * FROM my_table");

// Process the result set


while (resultSet.next()) {
// Retrieve data from the result set
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// Print the data
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the ResultSet, Statement, and Connection objects
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Output
ID: 1, Name: John
ID: 2, Name: Alice
ID: 3, Name: Bob

JDBC Connection class

The JDBC Connection class, java.sql.Connection, represents a database connection to a relational


database. Before you can read or write data from and to a database via JDBC, you need to open a
connection to the database.

Loading the JDBC Driver

The first thing you need to do before you can open a JDBC connection to a database is to load the
JDBC driver for the database.

Class.forName("driverClassName");

Each JDBC driver has a primary driver class that initializes the driver when it is loaded. For instance,
to load the H2Database driver, you write this:

Class.forName("org.h2.Driver");

Opening the JDBC Connection

open a JDBC Connection by call the java.sql.DriverManager class method getConnection().

The first method variant only takes a URL to the database as parameter. This is how
calling getConnection() only with the URL as parameter looks:

String url = "jdbc:h2:~/test"; //database specific url.

Connection connection =
DriverManager.getConnection(url);

Open Connection With URL, User and Password

The second variant of getConnection() takes both a database URL, a user


name and a password as parameters. Here is an example of calling that
variant of getConnection() :

String url = "jdbc:h2:~/test"; //database specific url.


String user = "sa";
String password = "";

Connection connection =
DriverManager.getConnection(url, user, password);
Open Connection With URL and Properties

The third variant of getConnection() takes a database URL and


a Properties object as parameter. Here is an example of calling this variant
of getConnection():

String url = "jdbc:h2:~/test"; //database specific url.

Properties properties = new Properties( );


properties.put( "user", "sa" );
properties.put( "password", "" );

Connection connection =
DriverManager.getConnection(url, properties);

The Properties object is used to pass special properties the database needs when opening the
connection

Closing the JDBC Connection

Once you are done using the database connection you should close it. This
is done by calling the Connection.close() method, like this:

connection.close();

(Same program here also you can use)

statements
The statement interface is used to create SQL basic statements in Java it
provides methods to execute queries with the database. There are different
types of statements that are used in JDBC as follows:
 Create Statement
 Prepared Statement
 Callable Statement

1. Create a Statement: From the connection interface, you can create


the object for this interface. It is generally used for general–purpose
access to databases and is useful while using static SQL statements
at runtime.

Syntax:
Statement statement = connection.createStatement();
Implementation: Once the Statement object is created, there are three ways
to execute it.

 boolean execute(String SQL): If the ResultSet object is retrieved,


then it returns true else false is returned. Is used to execute SQL
DDL statements or for dynamic SQL.
 int executeUpdate(String SQL): Returns number of rows that are
affected by the execution of the statement, used when you need a
number for INSERT, DELETE or UPDATE statements.
 ResultSet executeQuery(String SQL): Returns a ResultSet object.
Used similarly as SELECT is used in SQL.

2. Prepared Statement represents a recompiled SQL statement, that can be


executed many times. This accepts parameterized SQL queries. In this, “?” is
used instead of the parameter, one can pass the parameter dynamically by
using the methods of PREPARED STATEMENT at run time.
Illustration:
Considering in the people database if there is a need to INSERT some
values, SQL statements such as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);

String query = "INSERT INTO people(name, age)VALUES(?, ?)";


Statement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
// where pstmt is an object name

Implementation: Once the PreparedStatement object is created, there are


three ways to execute it:
 execute(): This returns a boolean value and executes a static SQL
statement that is present in the prepared statement object.
 executeQuery(): Returns a ResultSet from the current prepared
statement.
 executeUpdate(): Returns the number of rows affected by the DML
statements such as INSERT, DELETE, and more that is present in
the current Prepared Statement.
1. Callable Statement are stored procedures which are a group of
statements that we compile in the database for some task, they are
beneficial when we are dealing with multiple tables with complex scenario
& rather than sending multiple queries to the database, we can
send the required data to the stored procedure & lower the logic executed
in the database server itself. The Callable Statement interface provided
by JDBC API helps in executing stored procedures.

Syntax: To prepare a CallableStatement

CallableStatement cstmt = con.prepareCall("{call


Procedure_name(?, ?}");
Implementation: Once the callable statement object is created
 execute() is used to perform the execution of the statement.

Remember to close these statement objects and release resources after you
finish using them to avoid memory leaks.

resultSet.close();
statement.close(); // or preparedStatement.close(); or
callableStatement.close();

ResultSet
The SQL statements that read data from a database query, return the data in a
result set. The SELECT statement is the standard way to select rows from a
database and view them in a result set. The java.sql.ResultSet interface represents
the result set of a database query.

A ResultSet object maintains a cursor that points to the current


row in the result set. The term "result set" refers to the row and
column data contained in a ResultSet object.

The methods of the ResultSet interface can be broken down into


three categories −

 Navigational methods − Used to move the cursor around.


 Get methods − Used to view the data in the columns of the
current row being pointed by the cursor.
 Update methods − Used to update the data in the columns
of the current row. The updates can then be updated in the
underlying database as well.
The cursor is movable based on the properties of the ResultSet.
These properties are designated when the corresponding
Statement that generates the ResultSet is created.

JDBC provides the following connection methods to create


statements with desired ResultSet −

 createStatement(int RSType, int RSConcurrency);


 prepareStatement(String SQL, int RSType, int
RSConcurrency);
 prepareCall(String sql, int RSType, int
RSConcurrency);

The first argument indicates the type of a ResultSet object and


the second argument is one of two ResultSet constants for
specifying whether a result set is read-only or updatable.

Type of ResultSet

The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.

The cursor can scroll forward and backward, and the result set is
ResultSet.TYPE_SCROLL_INSENSITIVE
by others to the database that occur after the result set was crea

The cursor can scroll forward and backward, and the result set is
ResultSet.TYPE_SCROLL_SENSITIVE.
others to the database that occur after the result set was create

Concurrency of ResultSet

The possible RSConcurrency are given below. If you do not specify any Concurrency type,
you will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description

ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default


ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

try {
Statement stmt =
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}

Navigating a Result Set

There are several methods in the ResultSet interface that involve moving the cursor,
including −

Methods & Description

public void beforeFirst() throws SQLException


1
Moves the cursor just before the first row.

public void afterLast() throws SQLException


2
Moves the cursor just after the last row.

public boolean first() throws SQLException


3
Moves the cursor to the first row.

public void last() throws SQLException


4
Moves the cursor to the last row.

public boolean absolute(int row) throws SQLException


5
Moves the cursor to the specified row.

Viewing a Result Set

The ResultSet interface contains dozens of methods for getting the data of the current row.
Methods & Description

public int getInt(String columnName) throws SQLException


1
Returns the int in the current row in the column named columnName.

public int getInt(int columnIndex) throws SQLException


2
Returns the int in the current row in the specified column index. The column index starts at 1, meaning th
the second column of a row is 2, and so on

Updating a Result Set

The ResultSet interface contains a collection of update methods


for updating the data of a result set.

Methods & Description

public void updateString(int columnIndex, String s) throws SQLExc


1
Changes the String in the specified column to the value of s.

public void updateString(String columnName, String s) throws SQ


2 Similar to the previous method, except that the column is specified by its n
index.

(Same program here also you can use)

handle database queries


To handle database queries in a Java application using JDBC, typically follow a sequence of steps:

1. Establish Database Connection: Connect to the database using JDBC.

2. Create Statement or PreparedStatement: Create a Statement or PreparedStatement object


to execute SQL queries.

3. Execute SQL Queries: Execute SQL queries using the created statement objects.

4. Process Results (if any): If the query returns results, process them.
5. Close Resources: Close the resources (such as ResultSet, Statement, and Connection)
properly to release database resources and prevent memory leaks.

(Same program here also you can use)

Networking– Inet Address class


Java InetAddress class represents an IP address. The java.net.InetAddress class
provides methods to get the IP of any host name for
example www.javatpoint.com, www.google.com, www.facebook.com, etc.

An IP address is represented by 32-bit or 128-bit unsigned number. An instance


of InetAddress represents the IP address with its corresponding host name.

There are two types of addresses: Unicast and Multicast. The Unicast is an
identifier for a single interface whereas Multicast is an identifier for a set of
interfaces.

IP Address

o An IP address helps to identify a specific resource on the network


using a numerical representation.
o Most networks combine IP with TCP (Transmission Control Protocol).
It builds a virtual bridge among the destination and the source.

There are two versions of IP address:

1. IPv4
IPv4 is the primary Internet protocol. It is the first version of IP deployed
for production in the ARAPNET in 1983. It is a widely used IP version to
differentiate devices on network using an addressing scheme. A 32-bit
addressing scheme is used to store 2 32 addresses that is more than 4
million addresses.

Features of IPv4:

o It is a connectionless protocol.
o It utilizes less memory and the addresses can be remembered easily with
the class based addressing scheme.
o It also offers video conferencing and libraries.
2. IPv6
IPv6 is the latest version of Internet protocol. It aims at fulfilling the need
of more internet addresses. It provides solutions for the problems present
in IPv4. It provides 128-bit address space that can be used to form a
network of 340 undecillion unique IP addresses. IPv6 is also identified with
a name IPng (Internet Protocol next generation).

Features of IPv6:

o It has a stateful and stateless both configurations.


o It provides support for quality of service (QoS).
o It has a hierarchical addressing and routing infrastructure.

TCP/IP Protocol
o TCP/IP is a communication protocol model used connect devices over a
network via internet.
o TCP/IP helps in the process of addressing, transmitting, routing and
receiving the data packets over the internet.
o The two main protocols used in this communication model are:
1. TCP i.e. Transmission Control Protocol. TCP provides the way to
create a communication channel across the network. It also helps in
transmission of packets at sender end as well as receiver end.
2. IP i.e. Internet Protocol. IP provides the address to the nodes
connected on the internet. It uses a gateway computer to check
whether the IP address is correct and the message is forwarded
correctly or not.

Java InetAddress Class Methods

public static InetAddress getByName(String host) throws UnknownHostException

It returns the instance of InetAddress containing LocalHost IP and name.

public static InetAddress getLocalHost() throws UnknownHostException

It returns the instance of InetAdddress containing local host name and address.

public String getHostName() - It returns the host name of the IP address.

public String getHostAddress()- It returns the IP address in string format.

Example of Java InetAddress Class


import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

Output:

Host Name: www.javatpoint.com


IP Address: 172.67.196.82

Java URL
The Java URL class represents an URL. URL is an acronym for Uniform
Resource Locator. It points to a resource on the World Wide Web. For
example:

1. https://www.javatpoint.com/java-tutorial

A URL contains many information:

1. Protocol: In this case, http is the protocol.


2. Server name or IP Address: In this case, www.javatpoint.com is the
server name.
3. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port
number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.
Constructors of Java URL class

URL(String spec)

Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)

Creates an instance of a URL from the given protocol, host, port number,
and file.

URL(String protocol, String host, int port, String file,


URLStreamHandler handler)

Creates an instance of a URL from the given protocol, host, port number,
file, and handler.

URL(String protocol, String host, String file)

Creates an instance of a URL from the given protocol name, host name,
and file name.

URL(URL context, String spec)

Creates an instance of a URL by parsing the given spec within a specified


context.

URL(URL context, String spec, URLStreamHandler handler)

Creates an instance of a URL by parsing the given spec with the specified
handler within a given context.

Commonly used methods of Java URL class


The java.net.URL class provides many methods. The important methods of URL class are
given below.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL


public String getPort() it returns the Port Number of the U

public String getFile() it returns the file name of the URL.

public String getAuthority() it returns the authority of the URL.

Example of Java URL class


//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}

Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

TCP and UDP Socket


TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are two of the most
commonly used transport layer protocols in computer networking. Both protocols facilitate
communication between devices on a network, but they have distinct characteristics that
make them suitable for different use cases.

TCP (Transmission Control Protocol):


1. Reliable Communication: TCP provides reliable, connection-oriented
communication. It ensures that data is delivered in order, without loss, duplication,
or errors.

2. Connection-Oriented: TCP establishes a connection between the sender and


receiver before transmitting data. It follows a three-way handshake to establish this
connection.

3. Flow Control and Congestion Control: TCP incorporates mechanisms for flow control
and congestion control to manage the rate of data transmission and prevent
network congestion.

4. Ordered Data Transfer: TCP guarantees that data sent from one end is received in
the same order by the other end.

5. Acknowledgment Mechanism: TCP uses acknowledgments to confirm that data has


been successfully received by the recipient. If acknowledgment is not received, TCP
retransmits the data.

TCP is suitable for applications that require reliable, error-free, and ordered delivery of data,
such as web browsing, email communication, file transfer (e.g., FTP), and database
communication.

UDP (User Datagram Protocol):

1. Connectionless Communication: UDP is connectionless and does not establish a


connection before transmitting data. Each packet is treated independently and may
take a different path to reach the destination.

2. Unreliable Communication: UDP does not provide reliability mechanisms like


acknowledgment, retransmission, or error correction. It's up to the application layer
to handle any reliability requirements.
3. Low Overhead: UDP has lower overhead compared to TCP because it lacks features
like connection establishment, acknowledgment, and flow control.

4. Fast Transmission: UDP is faster than TCP since it does not have to wait for
acknowledgment or retransmission of lost data.

5. Broadcast and Multicast Support: UDP supports broadcasting and multicasting,


allowing a single packet to be sent to multiple recipients simultaneously.

UDP is suitable for applications that prioritize speed and can tolerate some degree of packet
loss, such as real-time audio and video streaming, online gaming, DNS (Domain Name
System), and SNMP (Simple Network Management Protocol).

JAVA BEAN
What is JavaBeans?
JavaBeans is a portable, platform-independent model written in Java Programming
Language. Its components are referred to as beans.

In simple terms, JavaBeans are classes which encapsulate several objects into a
single object. It helps in accessing these object from multiple places. JavaBeans
contains several elements like Constructors, Getter/Setter Methods and much more.

JavaBeans has several conventions that should be followed:

 Beans should have a default constructor (no arguments)


 Beans should provide getter and setter methods

o A getter method is used to read the value of a readable property

o To update the value, a setter method should be called

 Beans should implement java.io.serializable, as it allows to save, store and restore


the state of a JavaBean you are working on

Simple example of JavaBean class


//Employee.java

package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}

How to access the JavaBean class?


To access the JavaBean class, we should use getter and setter methods.

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}

javaBean Properties
A JavaBean property is a named feature that can be accessed by the user
of the object. The feature can be of any Java data type, containing the
classes that you define.

A JavaBean property may be read, write, read-only, or write-only.


JavaBean features are accessed through two methods in the JavaBean's
implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would
be getFirstName() to read that property. This method is called the
accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would
be setFirstName() to write that property. This method is called the
mutator.

Advantages of JavaBean
The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another


application.
o It provides an easiness to reuse the software components.

Disadvantages of JavaBean
The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may
lead to the boilerplate code.

RMI
The RMI (Remote Method Invocation) is an API that provides a mechanism
to create distributed application in java. The RMI allows an object to
invoke methods on an object running in another JVM.

The RMI provides remote communication between the applications using


two objects stub and skeleton.

RMI uses stub and skeleton object for communication with the remote
object.

A remote object is an object whose method can be invoked from another


JVM.

stub
The stub is an object, acts as a gateway for the client side. All the
outgoing requests are routed through it. It resides at the client side and
represents the remote object. When the caller invokes method on the stub
object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual
Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton
The skeleton is an object, acts as a gateway for the server side object. All
the incoming requests are routed through it. When the skeleton receives
the incoming request, it does the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

Java RMI Example


The is given the 6 steps to write the RMI program.

1. Create the remote interface


2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton
objects using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

1) create the remote interface


For creating the remote interface, extend the Remote interface and
declare the RemoteException with all the methods of the remote
interface. Here, we are creating a remote interface that extends the
Remote interface. There is only one method named add() and it declares
RemoteException.

1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }

2) Provide the implementation of the remote interface


Now provide the implementation of the remote interface. For providing
the implementation of the Remote interface, we need to

o Either extend the UnicastRemoteObject class,


o or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a


constructor that declares RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements A
dder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }

3) create the stub and skeleton objects using the rmic tool.

Next step is to create stub and skeleton objects using the rmi compiler.
The rmic tool invokes the RMI compiler and creates stub and skeleton
objects.

1. rmic AdderRemote

4) Start the registry service by the rmiregistry tool


Now start the registry service by using the rmiregistry tool. If you don't
specify the port number, it uses a default port number. In this example,
we are using the port number 5000.

1. rmiregistry 5000

5) Create and run the server application


Now rmi services need to be hosted in a server process. The Naming class
provides methods to get and store the remote object. The Naming class
provides 5 methods.

1. public static java.rmi.Remote lookup(java.lang.String) throws


java.rmi.NotBoundException,
java.net.MalformedURLException, java.rmi.RemoteException;
2. public static void bind(java.lang.String, java.rmi.Remote)
throws java.rmi.AlreadyBoundException,
java.net.MalformedURLException, java.rmi.RemoteException;

3. public static void unbind(java.lang.String) throws


java.rmi.RemoteException, java.rmi.NotBoundException,
java.net.MalformedURLException;

4. public static void rebind(java.lang.String, java.rmi.Remote)


throws java.rmi.RemoteException,
java.net.MalformedURLException;

5. public static java.lang.String[] list(java.lang.String) throws


java.rmi.RemoteException, java.net.MalformedURLException;

In this example, we are binding the remote object by the name sonoo.

import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}

6) Create and run the client application


At the client we are getting the stub object by the lookup() method of the
Naming class and invoking the method on this object. In this example, we
are running the server and client applications, in the same machine so we
are using localhost. If you want to access the remote object from another
machine, change the localhost to the host name (or IP address) where the
remote object is located.

You might also like