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


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