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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。