Java Long.shortValue()方法

原文:https://www.studytonight.com/java-wrapper-class/java-long-shortvalue-method

Java shortValue()方法属于java.lang包的Long 类。此方法在缩小图元转换(将较高的数据类型转换为较低的数据类型)后,返回 Long 对象的短等效物

简而言之,该方法用于将长对象转换为短值。

语法:

public short shortValue()

参数:

此方法中没有传递任何参数。

返回:

Short类型对象的数字等价物在转换后创建。

例 1:

在这里,使用shortValue()函数,长值被转换成它的数值短等价物。

import java.lang.Long;

public class StudyTonight {
  public static void main(String[] args) {
    //converting long object into short
    Long x = 99L;
    short i = x.shortValue();
    System.out.println(" Equivalent short value is " + i);

    Long y = 23L;
    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 );
      long i = sc.nextLong();
      Long n = i;
      short val = n.shortValue();
      System.out.println("Short Value is: " + val);
    }
    catch(Exception e) {
      System.out.println("not a valid long");
    }
  }
}

输入需要转换的数值:88 短数值为:88

                                                                                        • T3】输入需要转换的数值:-556 短数值为:-556
                                                                            • *输入需要转换的数值:0x522 不是有效的长数值

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。