Sobes.tech
Junior — Middle

Can two variables contain a reference to the same object in memory?

sobes.tech AI

Answer from AI

Yes, in Java, two variables can contain a reference to the same object in memory. This occurs when both variables point to the same instance of a class. For example:

StringBuilder sb1 = new StringBuilder("Hello");
StringBuilder sb2 = sb1; // sb2 references the same object as sb1

sb2.append(" World");
System.out.println(sb1.toString()); // Will output "Hello World"

In this example, changes made through sb2 are reflected when accessing sb1, since both variables refer to the same object.