📜  Java中的字节 compareTo() 方法及示例

📅  最后修改于: 2022-05-13 01:54:43.028000             🧑  作者: Mango

Java中的字节 compareTo() 方法及示例


Byte 类的compareTo()方法是Java中的一个内置方法,用于将给定的 Byte 类型对象与调用compareTo()方法的 Byte 实例进行比较。

句法

ByteObject.compareTo(Byte a)

参数:它将一个Byte类型的对象a作为输入,该对象将与调用compareTo方法的Byte对象的实例进行比较。

返回值:它返回一个int值。它返回:

  • 0 如果 'a 等于 'b,
  • 正值“a”大于“b”,
  • 负值“b”大于“a”

下面是Java中 compareTo() 方法的实现:

示例 1:

// Java code to demonstrate
// Byte compareTo() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // creating a Byte object
        Byte a = new Byte("20");
  
        // creating a Byte object
        Byte b = new Byte("20");
  
        // compareTo method in Byte class
        int output = a.compareTo(b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 20 and 20 : 0

示例 2:

// Java code to demonstrate
// Byte compareTo() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // creating a Byte object
        Byte a = new Byte("20");
  
        // creating a Byte object
        Byte b = new Byte("10");
  
        // compareTo method in Byte class
        int output = a.compareTo(b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 20 and 10 : 10

示例 3:

// Java code to demonstrate
// Byte compareTo() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // creating a Byte object
        Byte a = new Byte("10");
  
        // creating a Byte object
        Byte b = new Byte("20");
  
        // compareTo method in Byte class
        int output = a.compareTo(b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 10 and 20 : -10