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.