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:

  • 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.

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 short variables.
ten = 10;
twenty = 20;
  • We use the 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.

  • Now we can compare ten with twenty.
compare(ten, twenty);

The compare method returns a value < 0 because the first value is less than the second value.

  • Then, we compare twenty with ten.
compare(twenty, ten);

The compare method returns a value > 0 because the first value is greater than the second value.

Free Resources