Short compare() method in Java

The compare() method of Short class is used to compare two primitive short values for numerical equality. As it is a static method therefore it can be used without creating any object of Short.

Syntax:

public static int compare(short x, short y)

Parameters: This method accepts two parameters:



  • x: which is the first Short object to be compared.
  • y: which is the Short object to be compared.

Return type : It returns an int value. It returns:

  • 0 if ‘x’ is equal to ‘y’,
  • a positive value ‘x’ is greater than ‘y’,
  • a negative value ‘x’ is lesser than ‘y’

Below is the implementation of compare() method in Java:
Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate
// Short compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 4;
  
        short b = 4;
  
        // compare method in Short class
        int output = Short.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}

chevron_right


Output:

Comparing 4 and 4 : 0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate
// Short compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 4;
  
        short b = 2;
  
        // compare method in Short class
        int output = Short.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}

chevron_right


Output:

Comparing 4 and 2 : 2

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to demonstrate
// Short compare() method
  
class GFG {
    public static void main(String[] args)
    {
  
        short a = 2;
  
        short b = 4;
  
        // compare method in Short class
        int output = Short.compare(a, b);
  
        // printing the output
        System.out.println("Comparing " + a
                           + " and " + b + " : "
                           + output);
    }
}

chevron_right


Output:

Comparing 2 and 4 : -2


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.