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


Java Byte compareTo()用法及代码示例



Byte类的compareTo()方法是Java中的一种内置方法,用于将给定的Byte类型对象与Byte实例调用compareTo()方法进行比较。

用法

ByteObject.compareTo(Byte a)

参数:它接受一个Byte类型的对象a作为输入,该对象将与调用compareTo方法的Byte对象的实例进行比较。


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

  • 如果'a等于'b,则为0,
  • 正值“ a”大于“ b”,
  • 负值“ b”大于“ a”

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

示例1:

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

示例2:

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

示例3:

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


相关用法


注:本文由纯净天空筛选整理自ShivamKD大神的英文原创作品 Byte compareTo() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。