I am preparing for a certification exam and I don’t understand this code:
Main:
public class TestStudent {
public static void main(String[] args) {
Student bob = new Student();
Student jian = new Student();
bob.name = "Bob";
bob.age = 19;
jian = bob;
jian.name = "Jian";
System.out.println("Bob's Name: " + bob.name);
}
}
Class:
public class Student {
public String name = "";
public int age = 0;
public String major = "Undeclared";
}
Why does this output “Bob’s Name: Jian”?
Bob.name was never set to Jian. Obviously it must be because “jian = bob;” but i thought that would only set jian variables to the same as bob. What is this concept called and where is it explained in java tutorials?
Assignments in Java do not copy objects, they copy references. After this assignment
your
jianis no longer pointing to theStudentobject that you have allocated and assigned tojian, it’s the same asbob, creating an alias to the same object. The originaljianis now irretrievably lost, becoming eligible for garbage collection.The following assingment
overwrites the name in the
bobvariable through itsjianalias, leading to the result that you see.