java.lang.Float shortValue()

Description

The shortValue() method of Float class is used to get the equivalent of this Float object in short primitive. This method is a little bit tricky to use since the float primitive can handle more precision than short value thus if we will use the this method we might lose the precision the original value has. Let’s say we have the following declaration Float value = new Float(7317483747.4847f);. Certainly the value 7317483747.4847 is still within range of Float but what will happen if we will convert it to short using shortValue() method? I will be discussing this thoroughly later on this document.

Method Syntax

public short shortValue()

Note: This method overrides the method shortValue in class Number.

Method Returns

The shortValue() method of Float class returns the value of this Float as a short after a narrowing primitive conversion.

Compatibility

Java 1.1

Discussion

The shortValue() method is used to transform this Float object to primitive short byte. This is basically the core functionality of this method. As we all know a float data type can have decimal digits, what will happen to that if we convert it to short? For example if we have the following expression: Float value = new Float(17.375f);. What will gonna happen is that, the decimal digit will get truncated if we use the floatValue method. What we mean we say the decimal digit will get truncated such that the value returned will be be 17.

Java Float shortValue() Example

Below is a simple java example on the usage of shortValue() method of Float class.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

import static java.lang.System.*;

/*
 * This example source code demonstrates the use of 
 * shortValue() method of Float class.
 */

public class FloatShortValueExample {

	public static void main(String[] args) {
		
		// Ask user input
		System.out.print("Enter Desired Value:");
		// declare the scanner object
		Scanner scan = new Scanner(System.in);
		// use scanner to get value from user console
		Float userInput = scan.nextFloat();
		// close the scanner object
		scan.close();		
		// convert the Float input to primitive short
		short value = userInput.shortValue();
		out.println("Value in short is " + value);
		
	}

}

Basically on the above example, we just ask for user input on the console and then we use the scanner object to get the float input. After that we assign the value to an Float wrapper class and we then get the value in primitive data type short using the shortValue() method of Float class.

Sample Output

Below is the sample output when you run the above example.

Float shortValue() Sample Output