Java - Long intValue() 方法



描述

Java Long intValue() 方法返回此 Long 值作為 int 型別的值。

宣告

以下是 java.lang.Long.intValue() 方法的宣告

public int intValue()

引數

返回值

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

異常

從具有正值的 Long 獲取 int 值示例

以下示例演示瞭如何使用 Long intValue() 方法從 Long 物件獲取 int 值。我們建立了一個 Long 變數,併為其賦值一個包含正 long 數的 Long 物件。然後,使用 intValue 方法獲取此物件的 int 值,並將其打印出來。

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 int
      int i = obj.intValue();
      System.out.println("Value of i = " + i);
   }
}

輸出

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

Value of i = 5

從具有負值的 Long 獲取 int 值示例

以下示例演示瞭如何使用 Long intValue() 方法從 Long 物件獲取 int 值。我們建立了一個 Long 變數,併為其賦值一個包含負 long 數的 Long 物件。然後,使用 intValue 方法獲取此物件的 int 值,並將其打印出來。

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 int
      int i = obj.intValue();
      System.out.println("Value of i = " + i);
   }
}

輸出

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

Value of i = -5

從具有零值的 Long 獲取 int 值示例

以下示例演示瞭如何使用 Long intValue() 方法從 Long 物件獲取 int 值。我們建立了一個 Long 變數,併為其賦值一個包含零值的 Long 物件。然後,使用 intValue 方法獲取此物件的 int 值,並將其打印出來。

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 int
      int i = obj.intValue();
      System.out.println("Value of i = " + i);
   }
}

輸出

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

Value of i = 0

從具有負零值的 Long 獲取 int 值示例

以下示例演示瞭如何使用 Long intValue() 方法從 Long 物件獲取 int 值。我們建立了一個 Long 變數,併為其賦值一個包含負零值的 Long 物件。然後,使用 intValue 方法獲取此物件的 int 值,並將其打印出來。

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 int
      int i = obj.intValue();
      System.out.println("Value of i = " + i);
   }
}

輸出

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

Value of i = 0
java_lang_long.htm
廣告
© . All rights reserved.