This question is from enthuware mock exam
My answer was s=null,sb=null
But the correct answer is s=aaa, sb=bbbaaabbb
My understanding of this code is, we are passing two object reference variables to method testRefs( ). Since this is pass-by-reference the called method can change the object the variable referred to.
Initial values of s="aaa" and sb = "bbb"
this makes str = "aaabbb";
correct me if I am wrong
Strings are immutable. In this case there are 2 string objects on heap - "aaa" and "aaabbb".
s refering to "aaa"
str refering to "aaabbb"
intially s was refering to "aaa", when the above statement exceutes s refers to "aaabbb" and the first reference is abadoned
after this statement sb value is "bbbaaabbb"
this code assigning null to both reference variables. when the control returns to main() method, println statement executes.
why the output in not null?
what is point of assigning null to str and sb reference variables?
Yes, your understanding is right. I want add some information to your explanation about making reference variables to null.
Generally , If you assign null to reference variable then it doesn't point to that object.
After execution of the above statement, str will refer to new String object.
Now s is null, so it doesn't point that new String object. That new String object (not String object in main method) is eligible for garbage collection.
sb is still pointing to StringBuilder object created in main method. So StringBuilder object in main method has two reference variables sb, sb .
With the execution of the above statement, sb in testRefs method doesn't point to StringBuilder object in main method. But sb in main method is still pointing to StringBuilder object in main method. So it doesn't eligible for garbage collection because it has reference variable.