The compareTo
method of the Short
class can be used to compare the current object’s Short
value to another Short
value.
The
Short
class wraps theShort
type in an object. TheShort
primitive data type is a 16-bit signed two’s complement integer that has a minimum value of-32,768
and a maximum value of32,767
(inclusive).
public int compareTo(Short b);
b
: an object of type Short
for comparison with the current object.0
if the current object value and the passed argument value are the same.
A positive value if the current object value is greater than the argument.
A negative value if the current object value is less than the argument.
The code below uses the compareTo
method to compare Short
values.
class ShortCompareToExample {public static void main( String args[] ) {Short val1 = 10;Short 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 3, we create a Short
object variable with the name val1
and value 10
.
In lines 5 and 6, we create another Short
value val2
with value 10
. We call the compareTo
method on the val1
object with val2
as an argument. We get 0
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 -1
as a result because val1
is less than val2
.
In lines 11 and 12, we change the value of val2
to 9
and call the compareTo
method on the val1
object with val2
as an argument. We get 1
as a result because val1
is greater than val2
.