Please consider the following bit of code :
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static List<String> arraylist=new ArrayList<String>();
//add hello n times to the list
public static void add_to_list(int n)
{
if(n==0)
{
return;
}
else
{
String b=new String("hello");
arraylist.add(b);
add_to_list(n-1);
}
}
public static void main(String args[]) throws IOException
{
add_to_list(5);
for(String s:arraylist)
{
System.out.println(s);
}
}
}
I have tried running this program multiple times and I get the same output as :
hello
hello
hello
hello
hello
My assumptions :
- String b goes out of the scope once the method add_to_list is executed
- I am referencing the arraylist reference indexes outside their scope
- Arraylist contains the reference of the strings created in the method.
Hence my question is :
- Is there a possibility that the references are cleaned up by the java collector before I print the value?
- Did I just get lucky and the Java collector did not run before I read those values?