What is the Byte.compareTo() method in Java?

The compareTo() method of the Byte class in Java can be used to compare one Byte object to another Byte object.

The Byte class wraps the byte type in an object.

The byte primitive data type is an 88-bit signed two’s complement integer that has a minimum value of 128-128 and a maximum value of 127127 (inclusive).

Syntax

The syntax of the compareTo() method is as follows:

public int compareTo(Byte b);

Return value

The compareTo() method returns one of the following:

  • If the specified Byte object is the same as the object passed as an argument, compareTo() returns 00.

  • If the specified Byte object is numerically greater than the object passed as an argument, compareTo() returns a positive integer.

  • If the specified Byte object is numerically less than the object passed as an argument, compareTo() returns a negative integer.

Code

The code below uses the compareTo() method to compare Byte objects.

class ByteCompareToExample {
public static void main( String args[] ) {
Byte val1 = 10;
Byte val2 = 10;
System.out.println("10, 10 : " + val1.compareTo(val2));
val2 = 11;
System.out.println("10, 11 : " + val1.compareTo(val2));
val2 = 9;
System.out.println("10, 9 : " + val1.compareTo(val2));
}
}

Explanation

In the code above:

  • In line 33, we create a Byte object variable with the name val1 and value 1010.

  • In lines 55 and 66, we create another Byte object val2 with value 1010. We call the compareTo() method on the val1 object with val2 as an argument. We get 00 as a result because the values are equal.

  • In lines 8 and 9, we change the value of val2 to 11 and call the compareTo() method on the val1 object with val2 as an argument. We get 1-1 as a result because val1 is less than val2.

  • In lines 1111 and 1212, we change the value of val2 to 99 and call the compareTo() method on the val1 object with val2 as an argument. We get 11 as a result because val1 is greater than val2.