## java.lang.Short compare(short x, short y)

## Description

The compare(short x, short y) method of Byte class compares two short values numerically. The value returned is identical to what would be returned by:

Short.valueOf(x).compareTo(Short.valueOf(y))## Method Syntax

public static int compare(short x, short y)

## Method Argument

Data Type | Parameter | Description |
---|---|---|

short | x | the first short to compare |

short | y | the second short to compare |

## Method Returns

The compare(short x, short y) method of Short class returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y.

## Compatibility

Requires Java 1.7 and up

## Java Short compare(short x, short y) Example

Below is a simple java example on the usage of compare(short x, short y) method of Short class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.javatutorialhq.java.examples; /* * This example source code demonstrates the use of * compare(short x, short y) method of Short class. */ public class CompareExample { public static void main(String[] args) { // assign new short primitives short x = 12; short y = 15; short z = 12; // x less than y int result = Short.compare(x, y); System.out.println("Result:"+result); // x equal to z result = Short.compare(x, z); System.out.println("Result:"+result); // y greater than z result = Short.compare(y, z); System.out.println("Result:"+result); } } |

Basically on the above example, we have assigned 3 short primitive x,y,and z. There are 3 examples provided, the first one is when we compare x and y, the second one is x and z, and the last is y and z.

In comparing x and y, the result is -3 which is the difference between x and y. Since the result is less than 0, then we can conclude that x is less than y.

On the second comparison between x and z, the result is 0. As you have already noticed the value of x and z is the same.

For the 3rd example, the comparison is done between y and z. The result would be 3 which is greater than 0. This result means that y is greater than z.

## Sample Output

Below is the sample output when you run the above example.