Java Byte compareTo()方法及示例
Byte类的 compareTo() 方法是Java中的一个内置方法,用于比较给定的Byte类型对象和调用 compareTo() 方法的Byte实例。
语法
ByteObject.compareTo(Byte a)
参数: 它接受一个字节类型的对象a作为输入,它将与调用 compareTo 方法的字节对象实例进行比较。
返回值: 它返回一个 int 值。它返回。
如果’a’等于’b’,返回0。正值’a’大于’b’。负值’b’大于’a’。下面是compareTo()方法在Java中的实现。
例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
