Open In App

Java Number.shortValue() Method

Last Updated : 15 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The shortValue() is an inbuilt method in Java from the java.lang.Number class. This method is used to convert the current number object into a short primitive type.

This may involve rounding or truncation because the short data type in Java is a 16-bit signed integer with a value range from -32,768 to 32,767. And if we convert a number larger than this range, it can cause data loss.

Syntax of shortValue() Method

public abstract short shortValue();

  • Parameters: This method does not accept any parameters. 
  • Return value: This method returns the numeric value represented by this object after conversion to type short.

Examples of Java Number.shortValue() Method

Example 1: In this example, we are going to convert the larger values.

Java
// Java program to demonstrate 
// shortValue() with large float and double values
import java.lang.Number;

public class Geeks {

    public static void main(String[] args) {

        // Large float number
        Float f = new Float(7854123456f);
        short shortFromFloat = f.shortValue();
        System.out.println("Float to short: " + shortFromFloat);

        // Large double number
        Double d = new Double(98774856);
        short shortFromDouble = d.shortValue();
        System.out.println("Double to short: " + shortFromDouble);
    }
}

Output
Float to short: -1
Double to short: 12104

Explanation: Here, both values exceeds the limit of the short data type so, the results wraps around due to data loss.


Example 2: In this example, we are going to do safe conversions with smaller values.

Java
// Java program to demonstrate 
// shortValue() with smaller, within-range values
import java.lang.Number;

public class Geeks {

    public static void main(String[] args) {

        // Float value within short range
        Float f = new Float(78f);
        System.out.println("Float to short: " 
        + f.shortValue());

        // Double value within short range
        Double d = new Double(56.23);
        System.out.println("Double to short: " 
        + d.shortValue());
    }
}

Output
Float to short: 78
Double to short: 56

Explanation: Here, the values are withing the valid short range. And the decimal values like 56.23 are truncated to 56 before converting.

Important Points:

  • This method is very useful when we need to extract numeric object to a short data type.
  • But we should cautiously use this method when working with large or floating point numbers because it can result in overflow.

Next Article
Practice Tags :

Similar Reads