Java - Integer shortValue() 方法



描述

Java Integer shortValue() 方法將此 Integer 的值作為 short 返回。

宣告

以下是 java.lang.Integer.shortValue() 方法的宣告

public short shortValue()

引數

返回值

此方法在轉換為 short 型別後返回此物件表示的數值。

異常

從正整數 Integer 獲取 short 值示例

以下示例演示瞭如何使用 Integer shortValue() 方法從 Integer 物件獲取 short 值。我們建立了一個 Integer 變數,併為其分配了一個包含正整數的 Integer 物件。然後使用 shortValue 方法,我們獲取此物件的 short 值,然後列印它。

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Value of s = 5

從負整數 Integer 獲取 short 值示例

以下示例演示瞭如何使用 Integer shortValue() 方法從 Integer 物件獲取 short 值。我們建立了一個 Integer 變數,併為其分配了一個包含負整數的 Integer 物件。然後使用 shortValue 方法,我們獲取此物件的 short 值,然後列印它。

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Value of s = -5

從正零整數 Integer 獲取 short 值示例

以下示例演示瞭如何使用 Integer shortValue() 方法從 Integer 物件獲取 short 值。我們建立了一個 Integer 變數,併為其分配了一個包含零值的 Integer 物件。然後使用 shortValue 方法,我們獲取此物件的 short 值,然後列印它。

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Value of s = 0

從負零值 Integer 獲取 short 值示例

以下示例演示瞭如何使用 Integer shortValue() 方法從 Integer 物件獲取 short 值。我們建立了一個 Integer 變數,併為其分配了一個包含負零值的 Integer 物件。然後使用 shortValue 方法,我們獲取此物件的 short 值,然後列印它。

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Value of s = 0
java_lang_integer.htm
廣告

© . All rights reserved.