Home » Java programming language

Java ObjectStreamField compareTo() Method with Example

ObjectStreamField Class compareTo() method: Here, we are going to learn about the compareTo() method of ObjectStreamField Class with its syntax and example.
Submitted by Preeti Jain, on April 12, 2020

ObjectStreamField Class compareTo() method

  • compareTo() method is available in java.io package.
  • compareTo() method is used to compare this ObjectStreamField with the given object (ob).
  • compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • compareTo() method does not throw an exception at the time of comparing two objects.

Syntax:

    public int compareTo(Object ob);

Parameter(s):

  • Object ob – represents the object to compare with this ObjectStreamField object.

Return value:

The return type of the method is int, it may return anyone of three value based at given below,

  • It returns negative integer (-1) when this object is less than the given object.
  • It returns positive integer (1) when this object is greater than the given object.
  • It returns positive integer (0) when this object is equal to the given object.

Example:

// Java program to demonstrate the example 
// of int compareTo(Object ob) method 
// of ObjectStreamField

import java.io.*;

public class CompareOfOSF {
 public static void main(String[] args) {
  // Instantiates two ObjectStreamClass for Long and
  // Double
  ObjectStreamClass o_sc1 = ObjectStreamClass.lookupAny(Long.class);
  ObjectStreamClass o_sc2 = ObjectStreamClass.lookupAny(Double.class);

  // By using getField() method is to get the field
  // value from Double and Long class
  ObjectStreamField field1 = o_sc1.getField("value");
  ObjectStreamField field2 = o_sc2.getField("value");

  int compare = field1.compareTo(field2);
  System.out.println("field1.compareTo(field2): " + compare);
 }
}

Output

field1.compareTo(field2): 0



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.