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

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

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

Byte 类的compare()方法是Java中的一个内置方法,用于比较两个字节值。

句法

Byte.compare(byte a, byte b)

参数:将两个字节值'a'和'b'作为要比较的参数的输入。

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

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

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

示例 1:

// Java code to demonstrate
// Byte compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // byte value 'a'
        byte a = 20;
  
        // byte value 'b'
        byte b = 20;
  
        // compare method of Byte class
        int output = Byte.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 20 and 20 : 0

示例 2:

// Java code to demonstrate
// Byte compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // byte value 'a'
        byte a = 20;
  
        // byte value 'b'
        byte b = 10;
  
        // compare method of Byte class
        int output = Byte.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 20 and 10 : 10

示例 3:

// Java code to demonstrate
// Byte compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        // byte value 'a'
        byte a = 10;
  
        // byte value 'b'
        byte b = 20;
  
        // compare method of Byte class
        int output = Byte.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 10 and 20 : -10