public void createObjects() {
// person 引用在栈中,Person对象实例在堆中
Person person = new Person("张三", 25);
// numbers 引用在栈中,数组对象在堆中
int[] numbers = new int[100];
}
public class MemoryExample {
public static void main(String[] args) {
// 方法调用信息压入栈
doCalculation();
// 方法返回后,相关栈帧弹出
}
public static void doCalculation() {
int x = 5; // x 在栈上
int y = 10; // y 在栈上
// numbers 引用在栈上,数组对象在堆上
int[] numbers = new int[3];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
// student 引用在栈上,Student对象在堆上
Student student = new Student("李四", 20);
// 调用方法,新的栈帧被创建
int result = calculateSum(x, y);
// 以下代码执行后,student和numbers的引用会从栈中移除
// 但堆中的对象仍然存在,直到垃圾回收器回收它们
}
public static int calculateSum(int a, int b) {
// a和b是参数,存在栈上
// temp也在栈上
int temp = a + b;
return temp;
// 方法返回后,a、b、temp从栈中弹出
}
}
class Student {
private String name; // 对象的属性存储在堆上
private int age; // 对象的属性存储在堆上
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}