杰瑞科技汇

Java中int和Integer有何区别?

Of course! This is a fundamental concept in Java that often confuses beginners. Here’s a detailed breakdown of the difference between int and Integer.

Java中int和Integer有何区别?-图1
(图片来源网络,侵删)

The Short Answer

  • int: A primitive data type. It's a basic building block of the language, not an object. It stores a raw integer value.
  • Integer: A wrapper class for int. It's a full-fledged object that can hold an int value, but it also has methods and can be null.

Detailed Comparison Table

Feature int (Primitive) Integer (Wrapper Class)
Type Primitive Data Type Reference Type (Object)
Default Value 0 null
Purpose Stores simple integer values. Used when an object is needed (e.g., in collections, generics).
Methods None. It's not an object. Has many useful methods like parseInt(), toString(), compareTo().
Memory Very memory-efficient (typically 4 bytes). Less efficient (uses more memory for the object overhead).
Can be null? No. It must hold a value. Yes. It can hold null, representing the absence of a value.
Example int score = 100; Integer score = 100; or Integer score = null;

Key Differences Explained with Examples

Let's dive deeper into the most important distinctions.

Primitive vs. Object (The Core Difference)

  • int is part of the language itself. It's not a class. You can't call methods on it.
  • Integer is a class from the java.lang package. It's a "box" that contains an int value. Because it's an object, you can call methods on it.
// int example
int myInt = 10;
// myInt.toString(); // COMPILE ERROR! int has no methods.
// Integer example
Integer myInteger = 10;
String stringVersion = myInteger.toString(); // This works! It's an object.
System.out.println("The integer as a string is: " + stringVersion); // Output: The integer as a string is: 10

null vs. Default Value

This is a critical distinction, especially when dealing with databases or APIs that can have "missing" values.

  • An int must have a value. Its default value is 0. If a field is uninitialized, it will be 0, which might be a valid value and hide bugs.
  • An Integer can be null, which explicitly means "no value" or "not set". This is much safer for representing optional data.
public class DefaultValueExample {
    int primitiveInt; // Default value is 0
    Integer wrapperInteger; // Default value is null
    public void printValues() {
        System.out.println("primitiveInt: " + primitiveInt); // Output: primitiveInt: 0
        System.out.println("wrapperInteger: " + wrapperInteger); // Output: wrapperInteger: null
        // This would cause a NullPointerException!
        // int value = wrapperInteger; // Error! Cannot convert null to int.
    }
}

Autoboxing and Unboxing (The Bridge Between Them)

Java provides a convenient feature to automatically convert between int and Integer to make your code cleaner.

  • Autoboxing: Automatically converting an int to an Integer.
  • Unboxing: Automatically converting an Integer to an int.

This happens implicitly by the Java compiler.

Java中int和Integer有何区别?-图2
(图片来源网络,侵删)
// Autoboxing: int -> Integer
int primitiveNum = 15;
Integer wrapperNum = primitiveNum; // The compiler does: Integer.valueOf(primitiveNum)
// Unboxing: Integer -> int
Integer anotherWrapper = 20;
int anotherPrimitive = anotherWrapper; // The compiler does: anotherWrapper.intValue()
// Example where it shines in collections
// Before generics (Java 1.4), you HAD to use wrappers in collections
List list = new ArrayList();
list.add(100); // Autoboxing happens here. 100 is converted to Integer(100)
// You can also perform arithmetic
Integer a = 10;
Integer b = 5;
Integer sum = a + b; // Unboxing (a and b become ints), addition, then Autoboxing (result becomes Integer)
System.out.println("Sum: " + sum); // Output: Sum: 15
// Be careful with null! This will crash.
Integer nullValue = null;
int result = nullValue; // NullPointerException! The compiler can't unbox null.

When to Use Which?

Use int when:

  • You need raw performance and memory efficiency (e.g., in tight loops, large arrays).
  • You are certain the value will always be present and never null.
  • You are declaring local variables or method parameters for simple numerical calculations.
  • This is your default choice.
// Perfect use case for int
public int calculateSum(int[] numbers) {
    int sum = 0;
    for (int number : numbers) {
        sum += number;
    }
    return sum;
}

Use Integer when:

  • You need to store a value in a collection that only accepts objects (e.g., List<Integer>, Map<String, Integer>).
  • You are using generics (since they cannot use primitive types).
  • You need to use methods from the Integer class, like Integer.parseInt("123").
  • You need to represent an optional value that can be null. This is very common when interacting with databases or JSON APIs.
// Perfect use case for Integer
import java.util.ArrayList;
import java.util.List;
public class UserData {
    private Integer userId; // User might not have an ID yet, so null is appropriate.
    private List<Integer> userPermissions;
    public UserData() {
        this.userPermissions = new ArrayList<>();
        // Start with no permissions
    }
    public void addPermission(int permissionId) {
        userPermissions.add(permissionId); // Autoboxing happens here
    }
}

Summary

Think of int as the simple, fast, and essential tool for basic numbers. Think of Integer as a more advanced, flexible tool that can be used in object-oriented contexts and can represent the absence of a value with null. Java's autoboxing and unboxing features make it easy to switch between them, but understanding the underlying difference is crucial for writing robust and bug-free code.

分享:
扫描分享到社交APP
上一篇
下一篇