Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Short.compareTo method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The compareTo method of the Short class can be used to compare the current object’s Short value to another Short value.

The Short class wraps the Short type in an object. The Short primitive data type is a 16-bit signed two’s complement integer that has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).

Syntax

public int compareTo(Short b);

Parameters

  • b: an object of type Short for comparison with the current object.

Return value

  • 0 if the current object value and the passed argument value are the same.

  • A positive value if the current object value is greater than the argument.

  • A negative value if the current object value is less than the argument.

Code

The code below uses the compareTo method to compare Short values.

class ShortCompareToExample {
public static void main( String args[] ) {
Short val1 = 10;
Short val2 = 10;
System.out.println("10, 10 : " + val1.compareTo(val2));
val2 = 11;
System.out.println("10, 11 : " + val1.compareTo(val2));
val2 = 9;
System.out.println("10, 9 : " + val1.compareTo(val2));
}
}

Explanation

In the code above:

  • In line 3, we create a Short object variable with the name val1 and value 10.

  • In lines 5 and 6, we create another Short value val2 with value 10. We call the compareTo method on the val1 object with val2 as an argument. We get 0 as a result because the values are equal.

  • In lines 8 and 9, we change the value of val2 to 11 and call the compareTo method on the val1 object with val2 as an argument. We get -1 as a result because val1 is less than val2.

  • In lines 11 and 12, we change the value of val2 to 9 and call the compareTo method on the val1 object with val2 as an argument. We get 1 as a result because val1 is greater than val2.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring