Saturday, October 11, 2025
HomeLanguagesJavaShort compareTo() method in Java with Examples

Short compareTo() method in Java with Examples

The compareTo() method of Short class is a built in method in Java which is used to compare twoShort objects numerically.

Syntax:

public int compareTo(Short otherShort)

Parameters : This method accepts a mandatory parameter otherShort which is the Short object to be compared.

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

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

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




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


Output:

Comparing 4 and 4 : 0

Example 2:




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


Output:

Comparing 4 and 2 : 2

Example 3:




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


Output:

Comparing 2 and 4 : -2
RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6720 POSTS0 COMMENTS
Nicole Veronica
11882 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6839 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS