Short compareTo() method in Java with Examples
Last Updated :
05 Dec, 2018
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:
class GFG {
public static void main(String[] args)
{
Short a = new Short( "4" );
Short b = new Short( "4" );
int output = a.compareTo(b);
System.out.println( "Comparing " + a
+ " and " + b + " : "
+ output);
}
}
|
Output:
Comparing 4 and 4 : 0
Example 2:
class GFG {
public static void main(String[] args)
{
Short a = new Short( "4" );
Short b = new Short( "2" );
int output = a.compareTo(b);
System.out.println( "Comparing " + a
+ " and " + b + " : "
+ output);
}
}
|
Output:
Comparing 4 and 2 : 2
Example 3:
class GFG {
public static void main(String[] args)
{
Short a = new Short( "2" );
Short b = new Short( "4" );
int output = a.compareTo(b);
System.out.println( "Comparing " + a
+ " and " + b + " : "
+ output);
}
}
|
Output:
Comparing 2 and 4 : -2
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...