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:
0if 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
bytevariables:
ten = 10;
twenty = 20;
- We used the
comparemethod of theByteclass 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
tenwithtwenty:
compare(ten, twenty);
The compare method returns values < 0 if the first value is less than the second value.
- Then, we compared
twentywithten:
compare(twenty, ten);
The compare method returns values > 0 if the first value is greater than the second value.