What is the Short.compare method in Java?
compare is a static method of the Short class that is used to compare two short values.
Syntax
public static int compare(short x, short y);
Parameters
The compare function takes in two short values as parameters.
Return value
This method returns:
-
0if both the values are the same. -
A value less than zero if
xis less thany. -
A value greater than zero if
xis greater thany.
Short.compare(x,y)
Case | Retturn Value |
x == y | 0 |
x < y | < 0 |
x > y | > 0 |
Code
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));}}
Explanation
In the code above:
- We create two
shortvariables.
ten = 10;
twenty = 20;
- We use the
comparemethod of theShortclass to compare theshortvalues. 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.
- Now we can compare
tenwithtwenty.
compare(ten, twenty);
The compare method returns a value < 0 because the first value is less than the second value.
- Then, we compare
twentywithten.
compare(twenty, ten);
The compare method returns a value > 0 because the first value is greater than the second value.