LAST UPDATED: OCTOBER 16, 2020
Java Integer shortValue() Method
Java shortValue()
method belongs to the Integer
class of the java.lang package. This method returns the short equivalent of the Integer object after a narrowing primitive conversion(conversion of higher data type into lower data type).
In short, this method is used to convert an Integer object into a short value.
Syntax:
public short shortValue()
Parameter:
No parameter is passed in this method.
Returns:
The numerical equivalent of the object of a short type is created after conversion.
Example 1:
Here, using the shortValue()
method and integer values are converted into its numerical short equivalent.
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
//converting integer object into short
Integer x = 99;
short i=x.shortValue();
System.out.println(" Equivalent short value is " +i);
Integer y = 23;
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);
int i = sc.nextInt();
Integer n = i ;
short val = n.shortValue();
System.out.println("Short Value is: " + val);
}
catch(Exception e)
{
System.out.println("not a valid integer");
}
}
}
Enter the value to be converted : 54
Short Value is: 54
************************************************
Enter the value to be converted : 0x559
not a valid integer
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.