Java Short.compareTo(Short anotherShort) example

Java Short.compareTo(Short anotherShort) example

By Yashwant Chavan, Views 3, Date 24-Apr-2018

In this java tutorial, You will learn how to use compareTo(Short anotherShort) method of Short class. This method compares two Short objects numerically. This method 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).

tags Java

Compares two Short objects numerically.

Syntax

public int compareTo(Short anotherShort)

Parameters

anotherShort - the Short to be compared.

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).

Java Short compareTo(Short anotherShort) example

  • Assign two short values.
  • firstValue.compareTo(secondValue);It will compare the firstValue to the secondValue and return a int value.
  • According to the int value it will print the string result.
package com.technicalkeeda;

public class App {

	public static void main(String[] args) {

		short value1 = 50;
		Short firstValue = new Short(value1);

		short value2 = 20;
		Short secondValue = new Short(value2);

		int result = firstValue.compareTo(secondValue);

		displayResult(result);

		value1 = 100;
		firstValue = new Short(value1);

		value2 = 200;
		secondValue = new Short(value2);

		result = firstValue.compareTo(secondValue);

		displayResult(result);

		value1 = 100;
		firstValue = new Short(value1);

		value2 = 100;
		secondValue = new Short(value2);

		result = firstValue.compareTo(secondValue);

		displayResult(result);

	}

	public static void displayResult(int result) {

		if (result == 0) {
			System.out.println("firstValue is numeratically equal to secondValue");
		} else if (result > 0) {
			System.out.println("firstValue is numeratically greater than the secondValue");
		} else if (result < 0) {
			System.out.println("firstValue is numeratically lesser than the secondValue");
		}
	}
}

output

firstValue is numeratically greater than the secondValue
firstValue is numeratically lesser than the secondValue
firstValue is numeratically equal to secondValue

Suggested Posts

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]