What is the Byte.compare method in Java?

The static method compare of the Byte class is used to compare two byte values.

Syntax


public static int compare(byte x, byte y);

Returns

This method returns:

  • 0 if both the values are the same.
  • A value less than zero, if the x < y.
  • A value greater than zero, if the x > y.

Byte.compare(x,y)

Case

Return Value

x == y

0

x < y

< 0

x > y

> 0

Code

class ByteCompare {
public static void main( String args[] ) {
byte ten = 10;
byte twenty = 20;
System.out.println("ten, ten : " + Byte.compare(ten, ten));
System.out.println("twenty, twenty : " + Byte.compare(twenty, twenty));
System.out.println("ten, twenty : " + Byte.compare(ten, twenty));
System.out.println("twenty, ten : " + Byte.compare(twenty, ten));
}
}

Explanation

In the code above:

  • We created two byte variables:
ten = 10;
twenty = 20;
  • We used the compare method of the Byte class to compare the byte values. First, we compared the same values:
ten, ten => 0
twenty, twenty => 0

The compare method returns 0 if both the comparing values are the same.

  • Then, we compared ten with twenty:
compare(ten, twenty);

The compare method returns values < 0 if the first value is less than the second value.

  • Then, we compared twenty with ten:
compare(twenty, ten);

The compare method returns values > 0 if the first value is greater than the second value.

Free Resources