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
Byteclass wraps thebytetype in an object.
The
byteprimitive data type is an -bit signed two’s complement integer that has a minimum value of and a maximum value of (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
Byteobject is the same as the object passed as an argument,compareTo()returns . -
If the specified
Byteobject is numerically greater than the object passed as an argument,compareTo()returns a positive integer. -
If the specified
Byteobject 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 , we create a
Byteobject variable with the nameval1and value . -
In lines and , we create another Byte object
val2with value . We call thecompareTo()method on theval1object withval2as an argument. We get as a result because the values are equal. -
In lines 8 and 9, we change the value of
val2to11and call thecompareTo()method on theval1object withval2as an argument. We get as a result becauseval1is less thanval2. -
In lines and , we change the value of
val2to and call thecompareTo()method on theval1object withval2as an argument. We get as a result becauseval1is greater thanval2.