📜  Java中的简短比较()方法

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

Java中的简短比较()方法

Short 类的compare()方法用于比较两个原始的 short 值是否相等。由于它是一个静态方法,因此可以在不创建任何 Short 对象的情况下使用它。

句法:

public static int compare(short x, short y)

参数:此方法接受两个参数:

  • x:这是要比较的第一个 Short 对象。
  • y:要比较的 Short 对象。

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

  • 0 如果“x”等于“y”,
  • 正值“x”大于“y”,
  • 负值“x”小于“y”

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

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

示例 2:

// Java code to demonstrate
// Short compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 4;
  
        short b = 2;
  
        // compare method in Short class
        int output = Short.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 4 and 2 : 2

示例 3:

// Java code to demonstrate
// Short compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 2;
  
        short b = 4;
  
        // compare method in Short class
        int output = Short.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}
输出:
Comparing 2 and 4 : -2