【发布时间】:2022-12-12 12:27:11
【问题描述】:
我在 java 中运行一个简单的测试:
public class LawAcademyInterview {
@Test
void question1() {
Student student = new Student(1, "adam",99);
System.out.println("Before set to null: "+student);
makeItNull(student);
System.out.println("After set to null: "+student);
if (student == null)
System.out.println("Student is null");
else
System.out.println("Student is NOT null");
}
public void makeItNull(Student student) {
student = null; // Intellij warning: The value 'null' assigned to 'student' is never used
}
以下是输出:
Before set to null: Student(rollNo=1, name=adam, marks=99)
After set to null: Student(rollNo=1, name=adam, marks=99)
Student is NOT null
有趣的是当我这样做时:
@Test
void question2() {
Student student = new Student(1, "adam", 99);
System.out.println("Before set to null: " + student);
student = null;
System.out.println("After set to null: " + student);
if (student == null)
System.out.println("Student is null");
else
System.out.println("Student is NOT null");
}
输出是:
Before set to null: Student(rollNo=1, name=adam, marks=99)
After set to null: null
Student is null
任何人都有一个很好的解释,因为这几天一直困扰着我。在面试高级开发人员角色时向我提出了这个问题。我知道,我感到羞耻...... :(
【问题讨论】:
-
student = null在你的方法中意味着你的方法内部的学生变量不再指向你的方法之外的学生变量指向的引用。
标签: java null object-reference