Java - Long shortValue() 方法



描述

Java Long shortValue() 方法将此 Long 的值作为 short 返回。

声明

以下是 java.lang.Long.shortValue() 方法的声明

public short shortValue()

参数

返回值

此方法在转换为 short 类型后返回此对象表示的数值。

异常

从具有正值的 Long 对象获取 short 值示例

以下示例演示了如何使用 Long shortValue() 方法从 Long 对象获取 short 值。我们创建了一个 Long 变量,并为其分配一个包含正整数的 Long 对象。然后使用 shortValue 方法,我们从该对象获取 short 值,然后打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {
      Long obj = new Long(5L);
 
      // returns the value of this Long as a short
      short s = obj.shortValue();
      System.out.println("Value of s = " + s);
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Value of s = 5

从具有负值的 Long 对象获取 short 值示例

以下示例演示了如何使用 Long shortValue() 方法从 Long 对象获取 short 值。我们创建了一个 Long 变量,并为其分配一个包含负整数的 Long 对象。然后使用 shortValue 方法,我们从该对象获取 short 值,然后打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {
      Long obj = new Long(-5L);
 
      // returns the value of this Long as a short
      short s = obj.shortValue();
      System.out.println("Value of s = " + s);
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Value of s = -5

从具有零值的 Long 对象获取 short 值示例

以下示例演示了如何使用 Long shortValue() 方法从 Long 对象获取 short 值。我们创建了一个 Long 变量,并为其分配一个包含零值的 Long 对象。然后使用 shortValue 方法,我们从该对象获取 short 值,然后打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {
      Long obj = new Long(0L);
 
      // returns the value of this Long as a short
      short s = obj.shortValue();
      System.out.println("Value of s = " + s);
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Value of s = 0

从具有负零值的 Long 对象获取 short 值示例

以下示例演示了如何使用 Long shortValue() 方法从 Long 对象获取 short 值。我们创建了一个 Long 变量,并为其分配一个包含负零值的 Long 对象。然后使用 shortValue 方法,我们从该对象获取 short 值,然后打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {
      Long obj = new Long(-0L);
 
      // returns the value of this Long as a short
      short s = obj.shortValue();
      System.out.println("Value of s = " + s);
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Value of s = 0
java_lang_long.htm
广告

© . All rights reserved.