Author: saqibkhan

  • Set Values

    A tuple has setAtX() methods to set value at particular index. For example Triplet class has following methods.

    • setAt0() − set value at index 0.
    • setAt1() − set value at index 1.
    • setAt2() − set value at index 2.

    Feature

    • Tuples are immutable. Each setAtX() returns a new tuple which is to be used to see the updated value.
    • Type of a position of a tuple can be changed using setAtX() method.

    Example

    Let’s see JavaTuples in action. Here we’ll see how to set values in a tuple using various ways.

    Create a java class file named TupleTester in C:\>JavaTuples.

    File: TupleTester.java

    package com.tutorialspoint;
    import org.javatuples.Pair;
    public class TupleTester {
       public static void main(String args[]){
    
      //Create using with() method
      Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));   
      Pair<String, Integer> pair1 = pair.setAt0("Updated Value");
      System.out.println("Original Pair: " + pair);
      System.out.println("Updated Pair:" + pair1);
      Pair<String, String> pair2 = pair.setAt1("Changed Type");
      System.out.println("Original Pair: " + pair);
      System.out.println("Changed Pair:" + pair2);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Output

    Verify the Output

    Original Pair: [Test, 5]
    Updated Pair:[Updated Value, 5]
    Original Pair: [Test, 5]
    Changed Pair:[Test, Changed Type]
    
  • Get Values

    A tuple has getValueX() methods to get values and getValue() a generic method to get value by index. For example Triplet class has following methods.

    • getValue(index) − returns value at index starting from 0.
    • getValue0() − returns value at index 0.
    • getValue1() − returns value at index 1.
    • getValue2() − returns value at index 2.

    Feature

    • getValueX() methods are typesafe and no cast is required, but getValue(index) is generic.
    • A tuple has getValueX() methods upto element count. For example, Triplet has no getValue3() method but Quartet has.
    • Semantic Classes KeyValue and LabelValue has getKey()/getValue() and getLabel()/getValue() instead of getValue0()/getValue1() methods.

    Example

    Let’s see JavaTuples in action. Here we’ll see how to get values from a tuple using various ways.

    Create a java class file named TupleTester in C:\>JavaTuples.

    File: TupleTester.java

    package com.tutorialspoint;
    import org.javatuples.KeyValue;
    import org.javatuples.Pair;
    public class TupleTester {
       public static void main(String args[]){
    
      //Create using with() method
      Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));   
      Object value0Obj = pair.getValue(0);
      Object value1Obj = pair.getValue(1);
      String value0 = pair.getValue0();
      Integer value1 = pair.getValue1();
      System.out.println(value0Obj);
      System.out.println(value1Obj);
      System.out.println(value0);
      System.out.println(value1);  
       KeyValue<String, Integer> keyValue = KeyValue.with(
         "Test", Integer.valueOf(5)
      );
      value0 = keyValue.getKey();
      value1 = keyValue.getValue();
      System.out.println(value0Obj);
      System.out.println(value1Obj);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Output

    Verify the Output

    Test
    5
    Test
    5
    Test
    5
    
  • Create Tuples

    A tuple using JavaTuple classes can be created using multiple options. Following are the examples −

    Using with() Methods

    Each tuple class has a with() method with corresponding parameters. For example −

    Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));
    Triplet<String, Integer, Double> triplet = Triplet.with("Test", Integer.valueOf(5), 
       Double.valueOf(32.1));	
    

    Using Constructor

    Each tuple class has a constructor with corresponding parameters. For example −

    Pair<String, Integer> pair = new Pair("Test", Integer.valueOf(5));
    Triplet<String, Integer, Double> triplet = new Triplet("Test", Integer.valueOf(5), 
       Double.valueOf(32.1));	
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Using Collections

    Each tuple class has a fromCollection() method with corresponding parameters. For example −

    Pair<String, Integer> pair = Pair.fromCollection(listOfTwoElements);	
    

    Using Iterable

    Each tuple class has a fromIterable() method to get elements in generic fashion. For example −

    // Retrieve three values from an iterable starting at index 5
    Triplet<Integer,Integer,Integer> triplet = Triplet.fromIterable(listOfInts, 5);
    

    Example

    Let’s see JavaTuples in action. Here we’ll see how to create tupels using various ways.

    Create a java class file named TupleTester in C:\>JavaTuples.

    File: TupleTester.java

    package com.tutorialspoint;
    import java.util.ArrayList;
    import java.util.List;
    import org.javatuples.Pair;
    
    public class TupleTester {
       public static void main(String args[]){
    
      //Create using with() method
      Pair&lt;String, Integer&gt; pair = Pair.with("Test", Integer.valueOf(5));   
      //Create using constructor()
      Pair&lt;String, Integer&gt; pair1 = new Pair("Test", Integer.valueOf(5)); 
      List&lt;Integer&gt; listOfInts = new ArrayList&lt;Integer&gt;();
      listOfInts.add(1);
      listOfInts.add(2);
      //Create using fromCollection() method
      Pair&lt;Integer, Integer&gt; pair2 = Pair.fromCollection(listOfInts);	  
      listOfInts.add(3);
      listOfInts.add(4);
      listOfInts.add(5);
      listOfInts.add(6);
      listOfInts.add(8);
      listOfInts.add(9);
      listOfInts.add(10);
      listOfInts.add(11);
      //Create using fromIterable() method
      // Retrieve three values from an iterable starting at index 5
      Pair&lt;Integer,Integer&gt; pair3 = Pair.fromIterable(listOfInts, 5);
      //print all tuples
      System.out.println(pair);
      System.out.println(pair1);
      System.out.println(pair2);
      System.out.println(pair3);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    [Test, 5]
    [Test, 5]
    [1, 2]
    [6, 8]
    
  • Environment Setup

    Local Environment Setup

    If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.

    Java SE is freely available from the link Download Java. So you download a version based on your operating system.

    Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories −

    Setting up the Path for Windows 2000/XP

    We are assuming that you have installed Java in c:\Program Files\java\jdk directory −

    • Right-click on ‘My Computer’ and select ‘Properties’.
    • Click on the ‘Environment variables’ button under the ‘Advanced’ tab.
    • Now, alter the ‘Path’ variable so that it also contains the path to the Java executable. Example, if the path is currently set to ‘C:\WINDOWS\SYSTEM32’, then change your path to read ‘C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin’.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Setting up the Path for Windows 95/98/M

    We are assuming that you have installed Java in c:\Program Files\java\jdk directory −

    • Edit the ‘C:\autoexec.bat’ file and add the following line at the end − ‘SET PATH=%PATH%;C:\Program Files\java\jdk\bin’

    Setting up the Path for Linux, UNIX, Solaris, FreeBS

    Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

    Example, if you use bash as your shell, then you would add the following line to the end of your ‘.bashrc: export PATH=/path/to/java:$PATH’

    Popular Java Editor

    To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

    • Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
    • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
    • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

    Download JavaTuples Archie

    Download the latest version of JavaTuples jar file from Maven Repository – JavaTuples. In this tutorial, javatuples-1.2.jar is downloaded and copied into C:\> javatuples folder.

    OSArchive name
    Windowsjavatuples-1.2.jar
    Linuxjavatuples-1.2.jar
    Macjavatuples-1.2.jar

    Set JavaTuples Environment

    Set the JavaTuples environment variable to point to the base directory location where JavaTuples jar is stored on your machine. Assuming, we’ve extracted javatuples-1.2.jar in JavaTuples folder on various Operating Systems as follows.

    OSOutput
    WindowsSet the environment variable JavaTuples to C:\JavaTuples
    Linuxexport JavaTuples=/usr/local/JavaTuples
    Macexport JavaTuples=/Library/JavaTuples

    Set CLASSPATH Variable

    Set the CLASSPATH environment variable to point to the JavaTuples jar location. Assuming, you have stored javatuples-1.2.jar in JavaTuples folder on various Operating Systems as follows.

    OSOutput
    WindowsSet the environment variable CLASSPATH to %CLASSPATH%;%JavaTuples%\javatuples-1.2.jar;.;
    Linuxexport CLASSPATH=$CLASSPATH:$JavaTuples/javatuples-1.2.jar:.
    Macexport CLASSPATH=$CLASSPATH:$JavaTuples/javatuples-1.2.jar:.
  • Overview

    Tuple

    Tuple is a sequence of objects which may or may not be of same type. Consider the following example −

    [12,"TutorialsPoint", java.sql.Connection@li757b]
    

    Above object is a tuple of three elements, an Integer, a string and a Connection Object.

    JavaTuple

    JavaTuples is a very simple library which offers ten different tuple classses which are sufficient to handle most of the tuple related requirements.

    • Unit<A> – 1 element
    • Pair<A,B> – 2 elements
    • Triplet<A,B,C> – 3 elements
    • Quartet<A,B,C,D> – 4 elements
    • Quintet<A,B,C,D,E> – 5 elements
    • Sextet<A,B,C,D,E,F> – 6 elements
    • Septet<A,B,C,D,E,F,G> – 7 elements
    • Octet<A,B,C,D,E,F,G,H> – 8 elements
    • Ennead<A,B,C,D,E,F,G,H,I> – 9 elements
    • Decade<A,B,C,D,E,F,G,H,I,J> – 10 elements

    Apart from these tuple classes, JavaTuples also provides two additional classes for semantics sake.

    • KeyValue<A,B>
    • LabelValue<A,B>

    All tuple classes are typesafe and immutable and implements following interfaces and methods.

    • Iterable
    • Serializable
    • Comparable<Tuple>
    • equals()
    • hashCode()
    • toString()

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Tuple vs List/Array

    List or Array can contain any number of elements but each element must be of same type whereas tuples can contain only specific number of elements, can have different type of elements but still are typesafe.

  • Database Application

    In the previous chapter, we created a sample RMI application where a client invokes a method which displays a GUI window (JavaFX).

    In this chapter, we will take an example to see how a client program can retrieve the records of a table in MySQL database residing on the server.

    Assume we have a table named student_data in the database details as shown below.

    +----+--------+--------+------------+---------------------+ 
    | ID | NAME   | BRANCH | PERCENTAGE | EMAIL               | 
    +----+--------+--------+------------+---------------------+ 
    |  1 | Ram    | IT     |         85 | [email protected]    | 
    |  2 | Rahim  | EEE    |         95 | [email protected]  | 
    |  3 | Robert | ECE    |         90 | [email protected] | 
    +----+--------+--------+------------+---------------------+ 
    

    Assume the name of the user is myuser and its password is password.

    Creating a Student Class

    Create a Student class with setter and getter methods as shown below.

    public class Student implements java.io.Serializable {   
       private int id, percent;   
       private String name, branch, email;    
      
       public int getId() { 
    
      return id; 
    } public String getName() {
      return name; 
    } public String getBranch() {
      return branch; 
    } public int getPercent() {
      return percent; 
    } public String getEmail() {
      return email; 
    } public void setID(int id) {
      this.id = id; 
    } public void setName(String name) {
      this.name = name; 
    } public void setBranch(String branch) {
      this.branch = branch; 
    } public void setPercent(int percent) {
      this.percent = percent; 
    } public void setEmail(String email) {
      this.email = email; 
    } }

    Defining the Remote Interface

    Define the remote interface. Here, we are defining a remote interface named Hello with a method named getStudents () in it. This method returns a list which contains the object of the class Student.

    import java.rmi.Remote; 
    import java.rmi.RemoteException; 
    import java.util.*;
    
    // Creating Remote interface for our application 
    public interface Hello extends Remote {  
       public List<Student> getStudents() throws Exception;  
    }

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Developing the Implementation Class

    Create a class and implement the above created interface.

    Here we are implementing the getStudents() method of the Remote interface. When you invoke this method, it retrieves the records of a table named student_data. Sets these values to the Student class using its setter methods, adds it to a list object and returns that list.

    import java.sql.*; 
    import java.util.*;  
    
    // Implementing the remote interface 
    public class ImplExample implements Hello {  
       
       // Implementing the interface method 
       public List<Student> getStudents() throws Exception {  
    
      List&lt;Student&gt; list = new ArrayList&lt;Student&gt;();   
    
      // JDBC driver name and database URL 
      String JDBC_DRIVER = "com.mysql.jdbc.Driver";   
      String DB_URL = "jdbc:mysql://localhost:3306/details";  
      
      // Database credentials 
      String USER = "myuser"; 
      String PASS = "password";  
      
      Connection conn = null; 
      Statement stmt = null;  
      
      //Register JDBC driver 
      Class.forName("com.mysql.jdbc.Driver");   
      
      //Open a connection
      System.out.println("Connecting to a selected database..."); 
      conn = DriverManager.getConnection(DB_URL, USER, PASS); 
      System.out.println("Connected database successfully...");  
      
      //Execute a query 
      System.out.println("Creating statement..."); 
      
      stmt = conn.createStatement();  
      String sql = "SELECT * FROM student_data"; 
      ResultSet rs = stmt.executeQuery(sql);  
      
      //Extract data from result set 
      while(rs.next()) { 
         // Retrieve by column name 
         int id  = rs.getInt("id"); 
         
         String name = rs.getString("name"); 
         String branch = rs.getString("branch"); 
         
         int percent = rs.getInt("percentage"); 
         String email = rs.getString("email");  
         
         // Setting the values 
         Student student = new Student(); 
         student.setID(id); 
         student.setName(name); 
         student.setBranch(branch); 
         student.setPercent(percent); 
         student.setEmail(email); 
         list.add(student); 
      } 
      rs.close(); 
      return list;     
    } }

    Server Program

    An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMI registry.

    Following is the server program of this application. Here, we will extend the above created class, create a remote object and register it to the RMI registry with the bind name hello.

    import java.rmi.registry.Registry; 
    import java.rmi.registry.LocateRegistry; 
    import java.rmi.RemoteException; 
    import java.rmi.server.UnicastRemoteObject; 
    
    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) UnicastRemoteObject.exportObject(obj, 0);  
         
         // Binding the remote object (stub) in the registry 
         Registry registry = LocateRegistry.getRegistry(); 
         
         registry.bind("Hello", stub);  
         System.err.println("Server ready"); 
      } catch (Exception e) { 
         System.err.println("Server exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
    } }

    Client Program

    Following is the client program of this application. Here, we are fetching the remote object and invoking the method named getStudents(). It retrieves the records of the table from the list object and displays them.

    import java.rmi.registry.LocateRegistry; 
    import java.rmi.registry.Registry; 
    import java.util.*;  
    
    public class Client {  
       private Client() {}  
       public static void main(String[] args)throws Exception {  
    
      try { 
         // Getting the registry 
         Registry registry = LocateRegistry.getRegistry(null); 
    
         // Looking up the registry for the remote object 
         Hello stub = (Hello) registry.lookup("Hello"); 
    
         // Calling the remote method using the obtained object 
         List&lt;Student&gt; list = (List)stub.getStudents(); 
         for (Student s:list)v { 
            
            // System.out.println("bc "+s.getBranch()); 
            System.out.println("ID: " + s.getId()); 
            System.out.println("name: " + s.getName()); 
            System.out.println("branch: " + s.getBranch()); 
            System.out.println("percent: " + s.getPercent()); 
            System.out.println("email: " + s.getEmail()); 
         }  
      // System.out.println(list); 
      } catch (Exception e) { 
         System.err.println("Client exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
    } }

    Steps to Run the Example

    Following are the steps to run our RMI Example.

    Step 1 − Open the folder where you have stored all the programs and compile all the Java files as shown below.

    Javac *.java   
    
    Stored Programs

    Step 2 − Start the rmi registry using the following command.

    start rmiregistry
    
    Start Execution

    This will start an rmi registry on a separate window as shown below.

    Separate Window

    Step 3 − Run the server class file as shown below.

    Java Server
    
    Run Server

    Step 4 − Run the client class file as shown below.

    java Client
    
    Client File
  • GUI Application

    In the previous chapter, we created a sample RMI application. In this chapter, we will explain how to create an RMI application where a client invokes a method which displays a GUI window (JavaFX).

    Defining the Remote Interface

    Here, we are defining a remote interface named Hello with a method named animation() in it.

    import java.rmi.Remote; 
    import java.rmi.RemoteException;  
    
    // Creating Remote interface for our application 
    public interface Hello extends Remote { 
       void animation() throws RemoteException; 
    }

    Developing the Implementation Class

    In the Implementation class (Remote Object) of this application, we are trying to create a window which displays GUI content, using JavaFX.

    import javafx.animation.RotateTransition;  
    import javafx.application.Application;  
    import javafx.event.EventHandler;   
    
    import javafx.scene.Group;  
    import javafx.scene.PerspectiveCamera;  
    import javafx.scene.Scene;  
    import javafx.scene.control.TextField;  
    import javafx.scene.input.KeyEvent;  
    import javafx.scene.paint.Color;  
    import javafx.scene.paint.PhongMaterial; 
      
    import javafx.scene.shape.Box;  
    import javafx.scene.text.Font;  
    import javafx.scene.text.FontWeight;
    import javafx.scene.text.Text;   
    import javafx.scene.transform.Rotate;  
    
    import javafx.stage.Stage;  
    import javafx.util.Duration;  
    
    // Implementing the remote interface 
    public class FxSample extends Application implements Hello {  
       @Override  
       public void start(Stage stage) { 
    
      // Drawing a Box  
      Box box = new Box();  
      // Setting the properties of the Box  
      box.setWidth(150.0);  
      box.setHeight(150.0);    
      box.setDepth(100.0);  
      // Setting the position of the box  
      box.setTranslateX(350);   
      box.setTranslateY(150);  
      box.setTranslateZ(50);  
      // Setting the text  
      Text text = new Text(
         "Type any letter to rotate the box, and click on the box to stop the rotation");
      // Setting the font of the text  
      text.setFont(Font.font(null, FontWeight.BOLD, 15));      
      // Setting the color of the text  
      text.setFill(Color.CRIMSON);  
      // Setting the position of the text  
      text.setX(20);  
      text.setY(50); 
      // Setting the material of the box  
      PhongMaterial material = new PhongMaterial();   
      material.setDiffuseColor(Color.DARKSLATEBLUE);   
      // Setting the diffuse color material to box  
      box.setMaterial(material);        
      // Setting the rotation animation to the box     
      RotateTransition rotateTransition = new RotateTransition();  
      // Setting the duration for the transition  
      rotateTransition.setDuration(Duration.millis(1000));  
      // Setting the node for the transition  
      rotateTransition.setNode(box);        
      // Setting the axis of the rotation  
      rotateTransition.setAxis(Rotate.Y_AXIS);  
      // Setting the angle of the rotation 
      rotateTransition.setByAngle(360);  
      // Setting the cycle count for the transition  
      rotateTransition.setCycleCount(50);  
      // Setting auto reverse value to false  
      rotateTransition.setAutoReverse(false);   
      // Creating a text filed  
      TextField textField = new TextField();    
      // Setting the position of the text field  
      textField.setLayoutX(50);  
      textField.setLayoutY(100);  
      // Handling the key typed event  
      EventHandler&lt;KeyEvent&gt; eventHandlerTextField = new EventHandler&lt;KeyEvent&gt;() {  
         @Override  
         public void handle(KeyEvent event) {  
            // Playing the animation  
            rotateTransition.play();  
         }            
      };               
      
      // Adding an event handler to the text feld  
      textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);  
      // Handling the mouse clicked event(on box)  
      EventHandler&lt;javafx.scene.input.MouseEvent&gt; eventHandlerBox =  
         new EventHandler&lt;javafx.scene.input.MouseEvent&gt;() {  
         @Override  
         public void handle(javafx.scene.input.MouseEvent e) {  
            rotateTransition.stop();   
         }  
      };  
      
      // Adding the event handler to the box   
      box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox); 
      // Creating a Group object 
      Group root = new Group(box, textField, text);  
      // Creating a scene object  
      Scene scene = new Scene(root, 600, 300);       
      // Setting camera  
      PerspectiveCamera camera = new PerspectiveCamera(false);  
      camera.setTranslateX(0);  
      camera.setTranslateY(0);  
      camera.setTranslateZ(0);  
      scene.setCamera(camera);   
      // Setting title to the Stage
      stage.setTitle("Event Handlers Example");  
      // Adding scene to the stage  
      stage.setScene(scene);  
      // Displaying the contents of the stage  
      stage.show();  
    } // Implementing the interface method public void animation() {
      launch();  
    } }

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Server Program

    An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry.

    Following is the server program of this application. Here, we will extend the above created class, create a remote object, and registered it to the RMI registry with the bind name hello.

    import java.rmi.registry.Registry; 
    import java.rmi.registry.LocateRegistry; 
    import java.rmi.RemoteException; 
    import java.rmi.server.UnicastRemoteObject; 
    
    public class Server extends FxSample { 
       public Server() {} 
       public static void main(String args[]) { 
    
      try { 
         // Instantiating the implementation class 
         FxSample obj = new FxSample();
      
         // Exporting the object of implementation class  
         // (here we are exporting the remote object to the stub) 
         Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);  
      
         // Binding the remote object (stub) in the registry 
         Registry registry = LocateRegistry.getRegistry(); 
         
         registry.bind("Hello", stub);  
         System.err.println("Server ready"); 
      } catch (Exception e) { 
         System.err.println("Server exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
    } }

    Client Program

    Following is the client program of this application. Here, we are fetching the remote object and invoking its method named animation().

    import java.rmi.registry.LocateRegistry; 
    import java.rmi.registry.Registry;  
    
    public class Client { 
       private Client() {} 
       public static void main(String[] args) {  
    
      try { 
         // Getting the registry 
         Registry registry = LocateRegistry.getRegistry(null); 
    
         // Looking up the registry for the remote object 
         Hello stub = (Hello) registry.lookup("Hello"); 
         
         // Calling the remote method using the obtained object 
         stub.animation(); 
         
         System.out.println("Remote method invoked"); 
      } catch (Exception e) {
         System.err.println("Client exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
    } }

    Steps to Run the Example

    Following are the steps to run our RMI Example.

    Step 1 − Open the folder where you have stored all the programs and compile all the Java files as shown below.

    Javac *.java
    
    Stored Programs

    Step 2 − Start the rmi registry using the following command.

    start rmiregistry
    
    Start Execution

    This will start an rmi registry on a separate window as shown below.

    Separate Window

    Step 3 − Run the server class file as shown below.

    Java Server
    
    Run Server

    Step 4 − Run the client class file as shown below.

    java Client
    
    Client Class

    Verification − As soon you start the client, you would see the following output in the server.

    Event Handler
  • RMI Application

    To write an RMI Java application, you would have to follow the steps given below −

    • Define the remote interface
    • Develop the implementation class (remote object)
    • Develop the server program
    • Develop the client program
    • Compile the application
    • Execute the application

    Defining the Remote Interface

    A remote interface provides the description of all the methods of a particular remote object. The client communicates with this remote interface.

    To create a remote interface −

    • Create an interface that extends the predefined interface Remote which belongs to the package.
    • Declare all the business methods that can be invoked by the client in this interface.
    • Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it.

    Following is an example of a remote interface. Here we have defined an interface with the name Hello and it has a method called printMsg().

    import java.rmi.Remote; 
    import java.rmi.RemoteException;  
    
    // Creating Remote interface for our application 
    public interface Hello extends Remote {  
       void printMsg() throws RemoteException;  
    } 

    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() {  
    
      System.out.println("This is an example RMI program");  
    } }

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Developing the Server Program

    An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry.

    To develop a server program −

    • Create a client class from where you want invoke the remote object.
    • Create a remote object by instantiating the implementation class as shown below.
    • Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server.
    • Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry.
    • Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters.

    Following is an example of an RMI server program.

    import java.rmi.registry.Registry; 
    import java.rmi.registry.LocateRegistry; 
    import java.rmi.RemoteException; 
    import java.rmi.server.UnicastRemoteObject; 
    
    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) UnicastRemoteObject.exportObject(obj, 0);  
         
         // Binding the remote object (stub) in the registry 
         Registry registry = LocateRegistry.getRegistry(); 
         
         registry.bind("Hello", stub);  
         System.err.println("Server ready"); 
      } catch (Exception e) { 
         System.err.println("Server exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
    } }

    Developing the Client Program

    Write a client program in it, fetch the remote object and invoke the required method using this object.

    To develop a client program −

    • Create a client class from where your intended to invoke the remote object.
    • Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry.
    • Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry.To this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object.
    • The lookup() returns an object of type remote, down cast it to the type Hello.
    • Finally invoke the required method using the obtained remote object.

    Following is an example of an RMI client program.

    import java.rmi.registry.LocateRegistry; 
    import java.rmi.registry.Registry;  
    
    public class Client {  
       private Client() {}  
       public static void main(String[] args) {  
    
      try {  
         // Getting the registry 
         Registry registry = LocateRegistry.getRegistry(null); 
    
         // Looking up the registry for the remote object 
         Hello stub = (Hello) registry.lookup("Hello"); 
    
         // Calling the remote method using the obtained object 
         stub.printMsg(); 
         
         // System.out.println("Remote method invoked"); 
      } catch (Exception e) {
         System.err.println("Client exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
    } }

    Compiling the Application

    To compile the application −

    • Compile the Remote interface.
    • Compile the implementation class.
    • Compile the server program.
    • Compile the client program.

    Or,

    Open the folder where you have stored all the programs and compile all the Java files as shown below.

    Javac *.java
    
    Stored Programs

    Executing the Application

    Step 1 − Start the rmi registry using the following command.

    start rmiregistry
    
    Start Execution

    This will start an rmi registry on a separate window as shown below.

    Separate Window

    Step 2 − Run the server class file as shown below.

    Java Server
    
    Run Server

    Step 3 − Run the client class file as shown below.

    java Client 
    
    Run Client

    Verification − As soon you start the client, you would see the following output in the server.

    Output
  • Introduction

    RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM.

    RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi.

    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.

    RMI Architecture

    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 an RMI Application

    The following points summarize how an RMI application works −

    • When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL.
    • When the client-side RRL receives the request, it invokes a method called invoke() of the object remoteRef. It passes the request to the RRL on the server side.
    • The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server.
    • The result is passed all the way back to the client.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Marshalling and Unmarshalling

    Whenever a client invokes a method that accepts parameters on a remote object, the parameters are bundled into a message before being sent over the network. These parameters may be of primitive type or objects. In case of primitive type, the parameters are put together and a header is attached to it. In case the parameters are objects, then they are serialized. This process is known as marshalling.

    At the server side, the packed parameters are unbundled and then the required method is invoked. This process is known as unmarshalling.

    RMI Registry

    RMI registry is a namespace on which all server objects are placed. Each time the server creates an object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are registered using a unique name known as bind name.

    To invoke a remote object, the client needs a reference of that object. At that time, the client fetches the object from the registry using its bind name (using lookup() method).

    The following illustration explains the entire process −

    Registry

    Goals of RMI

    Following are the goals of RMI −

    • To minimize the complexity of the application.
    • To preserve type safety.
    • Distributed garbage collection.
    • Minimize the difference between working with local and remote objects.
  • No Overload

    A class is not allowed to have two overloaded methods that can have the same signature after type erasure.

    class Box  {
       //Compiler error
       //Erasure of method print(List<String>) 
       //is the same as another method in type Box
       public void print(List<String> stringList) { }
       public void print(List<Integer> integerList) { }
    }