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

ความแตกต่างระหว่าง Integer และ int ใน Java

Integer (Wrapper Class) vs int (Primitive Type)

  • Integer เป็น Wrapper Class ส่วน int เป็น Primitive Data Type
  • int เก็บค่า 32-bit signed two's complement integer ส่วน Integer ห่อหุ้ม int ไว้ใน Object
  • Integer ใช้เป็นอาร์กิวเมนต์เมธอดที่ต้องการ Object, int ใช้สำหรับคำนวณเลขคณิต
  • int เก็บค่าในหน่วยความจำโดยตรง, Integer แปลง int ↔ Object
  • ตัวแปร int เป็น mutable (ยกเว้น final), Integer เป็น immutable (มีค่า int อยู่ 1 ค่า)

ตัวอย่าง 1: ใช้ int (Primitive)


public class PrimitiveDataTypeTest {
    public static void main(String[] args) {
        int a = 20;
        int b = 40;
        int result = a + b;
        System.out.println("Result is: " + result);
    }
}

ผลลัพธ์

Result is: 60

ตัวอย่าง 2: ใช้ Integer (Wrapper)


public class WrapperClassTest {
    public static void main(String[] args) {
        int a = 20;
        Integer b = Integer.valueOf(a); // Autoboxing
        System.out.println("Converted Value of b is: " + b);
        
        Integer c = new Integer(30);
        int d = c.intValue(); // Unboxing
        System.out.println("Converted Value of d is: " + d);
    }
}

ผลลัพธ์


Converted Value of b is: 20
Converted Value of d is: 30

Autoboxing & Unboxing (Java 5+)

  • Autoboxing: int → Integer อัตโนมัติ (Integer b = a;)
  • Unboxing: Integer → int อัตโนมัติ (int d = c;)

เมื่อไหร่ควรใช้ตัวไหน?

สถานการณ์แนะนำ
คำนวณคณิตศาสตร์, loop counter, array indexint (เร็วกว่า, ใช้หน่วยความจำน้อยกว่า)
Collection (ArrayList, HashMap), GenericInteger (ต้องการ Object)
ค่าที่อาจเป็น nullInteger (int ไม่สามารถเป็น null ได้)
Method parameter ที่ต้องการ ObjectInteger