java.lang.Byte compare()


The compare() method of Byte class is used simply to compare two byte values on which one is higher. The compare(byte x, byte y) returns the int equivalent of comparing the method argument x and y. All the wrapper class has their own implementation of the compare method which gave us a lot of flexibility in comparing two numbers regardless of what data type is. It might be argued to use our own comparator instead, but designing a good comparator requires a lot of time and deligence. This method is more robust and will rely on the inherent behaviour of the compare method of the wrapper classes. Both ways has their pros and cons, it’s up to the java programmer to decide which suits him best.

Important Notes:

  • The method  compare(byte x, byte y) will yield the same result as Byte.valueOf(x).compareTo(Byte.valueOf(y))

Method Syntax

public static int compare(byte x, byte y)

Method Argument

Data Type Parameter Description
byte x the first byte to compare
byte y the second byte to compare

Method Returns

The compare() method of Byte class returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y.


Requires Java 1.7 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 compare 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.

Java Byte compare(byte x, byte y) Example

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

Basically on the above example, we have declared three Byte values. We then use the compare 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.