• Post Reply Bookmark Topic Watch Topic
  • New Topic

Please explain the output of the program.  RSS feed

 
Nilesh Srivastava
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain me in detail the output of the program;
import java.util.*;
public class InfiniteRecursion {
public String toString() {
return " InfiniteRecursion address: "
+ this + "\n";
}
public static void main(String[] args) {
ArrayList v = new ArrayList();
for(int i = 0; i < 10; i++)
v.add(new InfiniteRecursion());
System.out.println(v);
}
}
thanks is advance
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nilesh,
When posting questions of this nature, it works well when the person asking the question includes an explanation of what the result of running the program is, as well as thoughts on why the result is the way it is, thoughts on any expected alternative result, and comments about any specific parts that might be causing confusion.
In this example, the toString() method concatenates a String literal to a reference to this. this is a reference to the current object. When you add an object reference to a String, the toString() method of the object is called. So, in this example, the toString() method calls the same toString() method, which calls the same toString() method, which calls the same toString() method, etc. until the JVM runs out of memory while trying to keep track of all those never ending method calls.
Make sense?
 
Nilesh Srivastava
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dirk,
Both for explaining me the solution to the problem as well as to tell me how to put ur question in best possible way.
 
Nilesh Srivastava
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dirk,
I still have some confusion in my mind.
Like u said that when we add an object to a String then toString() method for that object is called and that's why the recursive call is made here to toString().
But what if we simply write
return this;
instead of concatenating it with a String.
Thanks
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nilesh
Try doing it. Think what happens and why. I guess you will get the answer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!