1

I found this question in one of the Java dumps and I would like to know how many object would be available after more code here 11 comment in the following code

public class Tahiti {
 Tahiti t;
 public static void main(String[] args) {
 Tahiti t = new Tahiti();
 Tahiti t2 = t.go(t);
 t2 = null;
 // more code here 11
 }
 Tahiti go(Tahiti t) {
 Tahiti t1 = new Tahiti();
 Tahiti t2 = new Tahiti();
 t1.t = t2;
 t2.t = t1;
 t.t = t2;
 return t1;
 }
}

My answer was one since the object reference by t2 object under main method has been set to null and because of that there isnt any reference pointing to that object but i found out that answer is 0

Could anyone help me on this? thanks

MAV
7,4674 gold badges33 silver badges47 bronze badges
asked Dec 26, 2013 at 12:46
5
  • 4
    You can't predict when garbage collection will occur. Commented Dec 26, 2013 at 12:48
  • 6
    @KevinBowersox This is not about predicting when GC will occur. It is about the reachability of objects (or if you prefer, its opposite---availability for collection). Commented Dec 26, 2013 at 12:51
  • 3
    Looks like all created references are reachable through t. Commented Dec 26, 2013 at 12:54
  • @Bart could you tell me how ?? Commented Dec 26, 2013 at 12:58
  • 1
    t1 and t2 have a circular reference to each other. t2 is assigned to t.t. Now all references are reachable through t. Commented Dec 26, 2013 at 13:10

1 Answer 1

3

How many objects are available?

All three. Variable t in main points directly to the first. That object's t field points at a second object, which was known as t2 within the go method. That object's t field points at the third object, known as t1 within the go method.

Proof:

System.out.println(t);
System.out.println(t.t);
System.out.println(t.t.t);

Assuming the VM manages to give all three created objects unique hashcodes (which it generally should), you should see something like:

Tahiti@107ebe1
Tahiti@10f11b8
Tahiti@544ec1

You could give the objects a String name; field to make distinguishing them easier.

answered Dec 26, 2013 at 13:10
Sign up to request clarification or add additional context in comments.

1 Comment

i am a bit confused could you please be more clear on That object's t field points at the third object, known as t1 within the go method comment of yours, thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.