當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。