Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ค่าสูงสุดของ Integer ใน Java (Integer.MAX_VALUE)

ค่าคงที่สำคัญของคลาส Integer

public class Demo {
    public static void main(String[] args) {
        System.out.println("The type is: " + Integer.TYPE);    // int
        System.out.println("The size is: " + Integer.SIZE);    // 32 (bits)
        System.out.println("The max value of integer is: " + Integer.MAX_VALUE); // 2147483647
    }
}

ผลลัพธ์

The type is: int
The size is: 32
The max value of integer is: 2147483647

คำอธิบาย:

  • Integer.MAX_VALUE = 231 - 1 = 2,147,483,647 (signed 32-bit)
  • Integer.MIN_VALUE = -231 = -2,147,483,648
  • Integer.SIZE = 32 bits
  • Integer.TYPE = primitive type int

คู่มือการใช้งาน

  • ตรวจสอบ overflow: if (a > Integer.MAX_VALUE - b) ก่อนบวก
  • Java 8+: ใช้ Math.addExact(a, b) โยน ArithmeticException ถ้า overflow
  • ต้องการช่วงกว้างกว่า: ใช้ long (63-bit signed) หรือ BigInteger
  • Unsigned integer: Java 8+ มี Integer.toUnsignedString(), Integer.compareUnsigned() แต่ยังไม่มี primitive unsigned int