java.lang.Short compareTo​(Short anotherShort)

Description

The compareTo​(Short anotherShort) method of Short class compares two Short objects numerically.

Specified by:

compareTo in interface Comparable<Short>

Method Syntax

public int compareTo​(Short anotherShort)

Method Argument

Data Type Parameter Description
Short anotherShort the Short to be compared.

Method Returns

The compareTo​(Short anotherShort) method of Short class returns the value 0 if this Short is equal to the argument Short; a value less than 0 if this Short is numerically less than the argument Short; and a value greater than 0 if this Short is numerically greater than the argument Short (signed comparison).

Compatibility

Requires Java 1.2 and up

Java Short compareTo​(Short anotherShort) Example

Below is a simple java example on the usage of compareTo​(Short anotherShort) method of Short class.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * compareTo​(Short x) method of Short class.
 */

public class CompareToExample {

	public static void main(String[] args) {

		// assign new Short Objects
		Short x = 12;
		Short y = 15;
		Short z = 12;
		
		
		// x less than y
		int result = x.compareTo(y);		
		System.out.println("Result:"+result);
		
		// x = z
		result = x.compareTo(z);
		System.out.println("Result:"+result);
		
		// y greater than z
		result = y.compareTo(z);
		System.out.println("Result:"+result);
		
		
		

		

	}

}

Basically on the above example, we have assigned 3 Short objects 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.

Java Short compareTo(short anotherShort) method example output