compare
is a static method of the Short
class that is used to compare two short
values.
public static int compare(short x, short y);
The compare
function takes in two short
values as parameters.
This method returns:
0
if both the values are the same.
A value less than zero if x
is less than y
.
A value greater than zero if x
is greater than y
.
Case | Retturn Value |
x == y | 0 |
x < y | < 0 |
x > y | > 0 |
The example below demonstrates how to use the Short.compare
method:
class ShortCompare {public static void main( String args[] ) {short ten = 10;short twenty = 20;System.out.println("ten, ten : " + Short.compare(ten, ten));System.out.println("twenty, twenty : " + Short.compare(twenty, twenty));System.out.println("ten, twenty : " + Short.compare(ten, twenty));System.out.println("twenty, ten : " + Short.compare(twenty, ten));}}
In the code above:
short
variables.ten = 10;
twenty = 20;
compare
method of the Short
class to compare the short
values. First, we compare the same values.compare(ten,ten);
compare(twenty, twenty);
Then, the compare
method returns 0
since the compared values are the same.
ten
with twenty
.compare(ten, twenty);
The compare
method returns a value < 0
because the first value is less than the second value.
twenty
with ten
.compare(twenty, ten);
The compare
method returns a value > 0
because the first value is greater than the second value.