Java Integer.shortValue()
方法
原文:https://www.studytonight.com/java-wrapper-class/java-integer-shortvalue-method
Java shortValue()
方法属于 java.lang 包的Integer
类。此方法在缩小图元转换(将较高数据类型转换为较低数据类型)后,返回整数对象的短等效物。
简而言之,该方法用于将整数对象转换为短值。
语法:
public short shortValue()
参数:
此方法中没有传递任何参数。
返回:
Short
类型对象的数字等价物在转换后创建。
例 1:
这里,使用shortValue()
方法,整数值被转换成其数值的短等价物。
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);
}
}
等值短值为 99 等值短值为 23
例 2:
这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等价的短值。
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");
}
}
}
输入需要转换的数值:54 短数值为:54
- *需要转换的数值:0x559 不是有效的整数
实时示例:
在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。