Java 有两个基本类型类别:基本类型(简单值直接存储)和引用类型(对象,其中变量持有对对象的引用/指针)。它们在内存、赋值和比较中的行为差异很大。
8 种基本类型
java
;
;
;
;
;
;
;
;
基本类型直接存储实际值,大小固定,不能为 null,存放在栈上(用于局部变量)。它们速度快且内存高效。
String name = "Ann"; // reference to a String object
int[] arr = {1, 2, 3}; // reference to an array object
List<String> list = new ArrayList<>(); // reference to a List object
Person p = new Person("Bob"); // reference to a Person object
引用变量持有一个引用(内存地址)指向存储在堆上的对象 — 不是对象本身。它们可以为 null。
// primitives — assignment COPIES the value (independent)
int a = 5;
int b = a; // b is a COPY
b = 10; // a is still 5
// references — assignment COPIES the reference (both point to the SAME object)
int[] x = {1, 2, 3};
int[] y = x; // y points to the SAME array
y[0] = 99; // x[0] is now 99 too! (shared object)
// == compares VALUES for primitives, but REFERENCES (identity) for objects
String s1 = new String("hi");
String s2 = new String("hi");
s1 == s2; // false — different objects (different references)
s1.equals(s2); // true — equals() compares CONTENT
这是一个常见的陷阱:对对象使用 == 比较身份(同一个对象?),而不是内容 — 使用 .equals() 来比较内容。
Integer boxed = 42; // Integer is the OBJECT wrapper for int (autoboxing)
int unboxed = boxed; // auto-unboxing back to primitive
List<Integer> nums; // collections need objects, not primitives
每个基本类型都有一个包装类(int→Integer 等),这样基本类型可以在需要对象的地方使用(集合、泛型)。
基本类型与引用类型的区别是 Java 的基础,也是许多微妙 bug 和行为的根源:赋值对基本类型复制值,但对对象共享引用(因此修改共享对象会影响所有引用),特别是 == 对对象比较的是身份(常见错误 — 内容比较使用 .equals())。
理解这一点会影响比较的正确性、方法参数(对象实际上是按引用值传递的)、null 处理(只有引用可以为 null)和性能(基本类型更轻量)。
这是编写正确 Java 代码的核心知识。