Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa Integer và int trong Java

Integer (Wrapper class) và int (kiểu dữ liệu nguyên thủy)

  • Khác biệt lớn nhất: Integer là wrapper class trong khi int là kiểu dữ liệu nguyên thủy (primitive).
  • int lưu trữ số nguyên 32-bit signed two's complement. Integer là lớp gói (wrap) kiểu int nguyên thủy vào một đối tượng.
  • Integer dùng làm tham số cho phương thức yêu cầu đối tượng; int dùng cho phương thức yêu cầu giá trị số nguyên (dùng trong biểu thức toán học).
  • int lưu giá trị nguyên trong bộ nhớ; Integer giúp chuyển int thành đối tượng và ngược lại.
  • Biến int là mutable (trừ khi đánh dấu final); Integer là immutable (chứa một giá trị int và không thay đổi).

Ví dụ 1: int nguyên thủy

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); 
    } 
}

Kết quả

Result is: 60

Ví dụ 2: Integer wrapper class

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); 
    } 
}

Kết quả

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

Tóm tắt

Đặc điểmintInteger
LoạiPrimitive typeWrapper class (Object)
Kích thước32-bitĐối tượng (header + int)
Giá trị mặc định0null
Có thể nullKhôngCó
Sử dụng trong CollectionKhông (cần wrapper)Có (ArrayList<Integer>)
Hiệu năngNhanh hơn, ít bộ nhớChậm hơn, tốn bộ nhớ
ImmutableKhông (mutable)Có

Autoboxing/Unboxing (Java 5+) tự động chuyển đổi giữa int và Integer.