Java Number intValue() 方法



描述

Java 的Number intValue() 方法將指定數字的值轉換為 int 值。這裡,我們稱之為“數字”,因為它可以是任何形式 - short、long、float、double。

int 值是一種僅儲存整數值的原始資料型別。它是一個 32 位帶符號的二進位制補碼整數,其範圍在 -231 到 231-1 之間。但是,在 Java SE 8 及更高版本中,int 關鍵字也可以表示範圍從 0 到 232-1 的無符號 32 位整數。

int 資料型別的預設值和大小分別為 0 和 4 位元組。

注意 - 此轉換可能涉及給定數字的舍入或截斷。

語法

以下是 Java Number intValue() 方法的語法

public abstract int intValue()

引數

此方法不接受任何引數。

返回值

此方法在轉換後返回 int 值。

從 Float 獲取 int 的示例

以下示例顯示了 Java Number intValue() 方法的用法。一個 float 值被賦予一個 Float 類引用變數。此值將使用此方法轉換為整數值,該方法在 Float 物件上呼叫。

package com.tutorialspoint;

public class NumberIntVal {
   public static void main(String[] args) {

      // get a number as float
      Float x = new Float(123456f);

      // print their value as int
      System.out.println("x as float:" + x + ", x as Integer:" + x.intValue());
   }
}

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

x as float:123456.0, x as Integer:123456

從 Double 獲取 int 的示例

在另一個示例中,我們將一個 double 值賦予一個 Double 類引用變數。此方法將在 Double 類物件上呼叫;並且賦予它的值將作為結果轉換為整數值。

package com.tutorialspoint;

public class NumberIntVal {
   public static void main(String[] args) {

      // get a number as double
      Double x = 5829.45d;
  
      // print their value as int
      System.out.println("x as long: " + x + ", x as Integer: " + x.intValue());
   }  
}

編譯並執行上述程式後的輸出如下 -

x as long: 5829.45, x as Integer: 5829

從 Long 獲取 int 的示例

這裡,我們將一個 long 值賦予一個 Long 類引用變數。該方法將在建立的 Long 類物件上呼叫,並且賦予它的值將轉換為整數值。

package com.tutorialspoint;

public class NumberIntVal {
   public static void main(String[] args) {

      // get a number as long
      Long x = (long) 792866;
  
      // print their value as int
      System.out.println("x as long: " + x + ", x as Integer: " + x.intValue());
   }  
}

讓我們編譯並執行給定的程式,輸出顯示如下 -

x as long: 792866, x as Integer: 792866

從 Byte 獲取 int 的示例

在此示例中,一個 byte 值被賦予 Byte 類引用變數並建立了一個物件。然後,該方法將在 Byte 物件上呼叫,並且 byte 值將作為結果轉換為整數值。

package com.tutorialspoint;

public class NumberIntVal {
   public static void main(String[] args) {

      // get a number as byte
      Byte x = 66;
  
      // print their value as int
      System.out.println("x as byte: " + x + ", x as Integer: " + x.intValue());
   }  
}

編譯並執行程式以獲取以下輸出 -

x as byte: 66, x as Integer: 66
java_lang_number.htm
廣告