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


Java Short compareTo()用法及代碼示例


Short類的compareTo()方法是Java中的內置方法,用於對兩個Short對象進行數值比較。

用法:

public int compareTo(Short otherShort)

參數:此方法接受強製參數otherShort,它是要比較的Short對象。


返回類型:它返回一個int值。它返回:

  • 如果“ otherShort”等於“ thisShort”,則為0,
  • 正值“ thisShort”小於“ otherShort”,
  • 負值“ otherShort”大於“ thisShort”

下麵是Java中compareTo()方法的實現:
示例1:

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

示例2:

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

示例3:

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


相關用法


注:本文由純淨天空篩選整理自Sruti Rai大神的英文原創作品 Short compareTo() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。