Java.lang Package Classes

Java Short - compare() Method



The java.lang.Short.compare() method is used to compare two short values numerically. The value returned is identical to what would be returned by: Short.valueOf(x).compareTo(Short.valueOf(y)).

Syntax

public static int compare(short x,
                          short y)

Parameters

x Specify the first short to compare.
y Specify the second short to compare.

Return Value

Returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y.

Exception

NA.

Example:

In the example below, the java.lang.Short.compare() method is used to compare given short values.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating short values
    short val1 = 5;
    short val2 = 5;
    short val3 = -5;

    //comparing short values 
    System.out.println("comparing val1 and val2: " + Short.compare(val1, val2)); 
    System.out.println("comparing val1 and val3: " + Short.compare(val1, val3)); 
    System.out.println("comparing val3 and val1: " + Short.compare(val3, val1));    
  }
}

The output of the above code will be:

comparing val1 and val2: 0
comparing val1 and val3: 10
comparing val3 and val1: -10

❮ Java.lang - Short