Java Float shortValue() Method

Java shortValue() method belongs to the Float class of the java.lang package. This method returns the short equivalent of the Float object after a narrowing primitive conversion(Conversion of higher data type into lower data type).

In short, this method is used to convert a Float object into a short value.

Syntax:

public short shortValue()  

Parameter:

No parameter is passed in this method.

Returns:

Returns the short value of the Float-object passed as the parameter.

Example 1:

Here, using the shortValue() method, the float values are converted into its numerical short equivalent.

import java.lang.Float;

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        //converting Float object into short
        Float x = 99.98f;
        short i = x.shortValue();
        System.out.println(" Equivalent short value is " +i);
          
        Float y = 23.45f;  
        short d = y.shortValue();  
        System.out.println(" Equivalent short value is " +d);
    }  
}


Equivalent short value is 99
Equivalent short value is 23

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent short value.

import java.util.Scanner;  
public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        try
        {
            System.out.print("Enter the value to be converted : ");  
            Scanner sc = new Scanner(System.in);  
            float i = sc.nextFloat();  
            Float n = i ;  
            short val = n.shortValue();  
            System.out.println("Short Value is: " + val);  
         }
         catch(Exception e)
         {
             System.out.println("not a valid float"); 
         }
    }
}


Enter the value to be converted : 695.845
Short Value is: 695
********************************************
Enter the value to be converted : -64.90
Short Value is: -64
********************************************
Enter the value to be converted : 0x68
not a valid float

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.