The compareTo()
method of the Byte
class in Java can be used to compare one Byte
object to another Byte
object.
The
Byte
class wraps thebyte
type in an object.
The
byte
primitive data type is an -bit signed two’s complement integer that has a minimum value of and a maximum value of (inclusive).
The syntax of the compareTo()
method is as follows:
public int compareTo(Byte b);
The compareTo()
method returns one of the following:
If the specified Byte
object is the same as the object passed as an argument, compareTo()
returns .
If the specified Byte
object is numerically greater than the object passed as an argument, compareTo()
returns a positive integer.
If the specified Byte
object is numerically less than the object passed as an argument, compareTo()
returns a negative integer.
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));}}
In the code above:
In line , we create a Byte
object variable with the name val1
and value .
In lines and , we create another Byte object val2
with value . We call the compareTo()
method on the val1
object with val2
as an argument. We get as a result because the values are equal.
In lines 8 and 9, we change the value of val2
to 11
and call the compareTo()
method on the val1
object with val2
as an argument. We get as a result because val1
is less than val2
.
In lines and , we change the value of val2
to and call the compareTo()
method on the val1
object with val2
as an argument. We get as a result because val1
is greater than val2
.