当前位置: 首页>>代码示例>>用法及示例精选>>正文


Java Short compare()用法及代码示例

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

用法:

public static int compare(short x, short y)

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


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

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

  • 如果“ x”等于“ y”,则为0,
  • 正值“ 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


相关用法

注:本文由纯净天空筛选整理自Sruti Rai大神的英文原创作品 Short compare() method in Java。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。