java.lang.Byte compareTo(Byte anotherByte)


The compareTo() method of Byte class is used to compare this Byte object to the byte method argument. This is a little bit different to the compare method because in compare method we put two byte data type together as method argument, while the compareTo method uses the current Byte value to compare to the float method argument. However the compareTo method returns the same value as that of the compare method.

Important Notes:

  • The method  compareTo(Byte anotherByte) is specified by compareTo in interface Comparable<Byte>

Method Syntax

public int compareTo(Byte anotherByte)

Method Argument

Data Type Parameter Description
Byte anotherByte the Byte to be compared.

Method Returns

The compareTo() method of Byte class returns the value 0 if this Byte is equal to the argument Byte; a value less than 0 if this Byte is numerically less than the argument Byte; and a value greater than 0 if this Byte is numerically greater than the argument Byte (signed comparison).


Requires Java 1.2 and up


To differentiate two numbers, usually our approach is to make use of if else conditional statements, and base on the results of the evaluation we determine the which one of the two numbers are greater or if they are equality. The compareTo method were devised as such that we can test the equality or compare two numbers without going the trouble of formulating the conditional statements. Well we might still be using the if condition however the conditional statements are more consistent now since we have only 3 possible values which are 0, <0, and >0.

The compareTo() method and compare() method yield the same result. The only difference is that if you want to just compare two primitive byte datatype without having to convert to Byte object, compare() method is already enough. However if you opt to compare two Byte object, the compareTo() method will do the job better.

Java Byte compareTo(Byte anotherByte) Example

Below is a simple java example on the usage of compareTo() method of Byte class.

Basically on the above example, we have declared three Byte values. We then use the compareTo method to do comparison of these three values. Based on the result of this method, we have devised a logic to display specific messages.

Sample Output

Below is the sample output when you run the above example.

java Byte compareTo() example output