Java Short compareTo()方法及实例

Java Short compareTo()方法及实例

Short类的 compareTo() 方法是Java中的一个内置方法,用于对两个Short对象进行数字比较。

语法

public int compareTo(Short otherShort)

参数 :该方法接受一个强制性参数 otherShort ,它是要比较的Short对象。

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

  • 如果’otherShort’等于’thisShort’,返回0。
  • 正值’thisShort’小于’otherShort’。
  • 负值’otherShort’大于’thisShort’。

下面是compareTo()方法在Java中的实现:

例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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程