Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping object in java

Tags:

java

The following code creates one array and one string object.

Now my questions are

  1. How many references to those objects exist after the code executes?
  2. Why?

Here is my code

String[] students = new String[10];
String studentName = "Peter Smith";
students[0] = studentName;
studentName = null;

I was thinking the answer is only one object i.e. students
But according to Oracle docs, Neither object is eligible for garbage collection

How should I infer the answer?

like image 815
Testaccount Avatar asked Nov 29 '22 01:11

Testaccount


1 Answers

How many references to those objects exist after the code executes?

  • One reference to a String[], obtainable through the expression students.
  • One reference to a String, obtainable through the expression students[0].

Why?

Essentially, the answer is that objects, not variables, can ever be eligible for garbage collection.

In your case, you have copied a reference of the string (which is an object) into the first slot of the array. Even after you clear (set to null) the initial variable, that same object is still visible from your code, by another name (and by "name" here I mean "expression", as described above). This is why the string is still not eligible for garbage collection.


For comparison, consider your code without the third line:

String[] students = new String[10];
String studentName = "Peter Smith";
studentName = null;

In this scenario, the string "Peter Smith" would indeed be eligible for garbage collection as you'd expect, because it's not obtainable anymore by any expression.


(All the above concern the Java language and leave any possible JVM optimizations aside.)

like image 103
Theodoros Chatzigiannakis Avatar answered Dec 08 '22 01:12

Theodoros Chatzigiannakis