This might be a very basic question but still I am not able to figure out why is the foll code giving stackoverflow exception in main??

public class HelloWorld{

     public static void main(String []args)
     {
        System.out.println("Hello World");
        Animal c = new Animal();

     }
} 
class Animal
{

Animal e = new Animal();

}
6:  Animal c = new Animal();    // creates a new Animal (1)
13: Animal e = new Animal();    // part of initialisation of Animal (1) - creates another new Animal (2)
13: Animal e = new Animal();    // part of initialisation of Animal (2) - creates another new Animal (3)
13: Animal e = new Animal();    // part of initialisation of Animal (3) - creates another new Animal (4)
...
13: Animal e = new Animal();    // part of initialisation of Animal (99999) - tries to create another new Animal but runs out of stack memory

Each Animal object has an instance variable named a. Every time a new Animal object is created, its e variable is initialized to new Animal(), which creates a new Animal object. So every time you create a new Animal object, you create another Animal object. So if you create one Animal object, you create an infinite amount of Animal objects. This leads to a stack overflow.

So why does the foll code doesnot give any exception although e points to object of same class??

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");

  a.foo();      

//Animal c = new Animal();

}} 
class Animal{
void foo(){
Animal e = new Animal();
}
   }

If your question is answered then please mark your thread "solved" for our knowledge base.
Thanks
J

So why does the foll code doesnot give any exception although e points to object of same class??

Your original code created a new Animal object every time that an Animal object was created. Your new code only creates a new Animal object if you call the foo method. You call the foo method on the first Animal that you create, but you don't call foo on the second Animal (the one that you create inside foo). So it stops there and no infinite recursion happens. If you added the line e.foo() inside your foo method, you would get infinite recursion again.

Thank you for your answers!Actually I sort of knew the answer but was not sure about it!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.