Java - Short intValue() 方法



Java Short intValue() 方法在進行擴充套件基本型別轉換(將較小的資料型別轉換為較大的資料型別)後,檢索給定 short 值的等效整數值。它是 Number 類的繼承成員。int 資料型別可以在 -2,147,483,648 到 2,147,483,647 的範圍內儲存整數。

簡而言之,使用此方法,Short 物件值將轉換為基本整數值。

例如,假設我們有一個 short 值“87”。給定 short 值的 int 值為“87”。

Short d1 = 87
Int value = 87

語法

以下是Java Short intValue()方法的語法:

public int intValue()

引數

此方法不接受任何引數。

返回值

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

從正值 Short 獲取 int 值示例

以下是一個示例,演示 Java Short intValue() 方法的使用。在這裡,我們使用正值建立一個 Short 物件。然後,列印它的整數值:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      /*
      * returns the short value represented by this object
      * converted to type int
      */
      Short obj = new Short("32");
      int i = obj.intValue();
      System.out.println("Value = " + i);
      obj = new Short("30");
      i = obj.intValue();
      System.out.println("Value = " + i);
   }
}

輸出

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

Value = 32
Value = 30

從 Short 物件獲取 int 值示例

以下是此函式的另一個示例:

package com.tutorialspoint;

import java.util.Scanner;

public class ShortDemo {
   public static void main(String[] args) {
      Short value1 = -35;
      Short value2 = -84;
      Short value3 = 987;
      System.out.println("Product of negative numbers = " + value1 * value2);
      System.out.println("Product of negative numbers = " + value1 * value3);
      int s = value1.intValue() * value2.intValue();
      System.out.println("Product of integer values = " + s);
   }
}

輸出

以下是上述程式碼的輸出:

Product of negative numbers = 2940
Product of negative numbers = -34545
Product of integer values = 2940

從具有最大值的 Short 物件獲取 int 值示例

在下面的示例中,建立了 short 變數“value”。然後將 MAX_VALUE 分配給此變數。然後,我們檢索其對應的整數值:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      Short value = Short.MAX_VALUE;
      System.out.println("The short MAX_VALUE is: " + value);
      
      // it returns int type value
      int result = value.intValue();
      System.out.println("The int value of short is: " + result);
   }
}

輸出

在執行上述程式後,輸出如下:

The short MAX_VALUE is: 32767
The int value of short is: 32767

從具有最小值的 Short 物件獲取 int 值示例

在下面的示例中,建立了 short 變數“value”。然後將 MIN_VALUE 分配給此變數。然後,我們檢索其對應的整數值:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      Short value = Short.MIN_VALUE;
      System.out.println("The short MIN_VALUE is: " + value);
      
      // it returns int type value
      int result = value.intValue();
      System.out.println("The int value of short is: " + result);
   }
}

輸出

在執行上述程式碼時,我們得到以下輸出:

The short MIN_VALUE is: -32768
The int value of short is: -32768
java_lang_short.htm
廣告