class A{
    A a=new A();
    void method(){
      System.out.println(a);
    }
    public static void main(String args[]){
        A b=new A();
        b.method();
    }
}

This code gives a run time error.What is the wrong with this code

let me guess...
stackoverflow?
each A instance has an A Object as instance variable
that instance variable in turn is, an instance of A, so, see previous line.

you're basically creating an endless number of instances of A, and yah ... that's about to go wrong.

Exception in thread "main" java.lang.StackOverflowError
This is the message that he's talking about.

yes, and the reason is what I mentioned in my previous post.

I'll try and explain it in a more structured way.

1. Every instance of A, becomes the 'owner' of a new 'member' of type A
2. This 'member' is also an instance of A, so: see step 1.

you're basically going over an infinite loop over these two steps, creating an infinite number of instances of A. All these instances occupy some space in your memory. for one, or two, or even for hundred references, this will never pose a problem. but in this case, you're creating an infinite number of references and you never make any of them eligible for collection (if you don't understand what I mean with this, google for 'Garbage collection').

even if you're working on the computer with the most memory space in the world, there will always be a limit to how much it can take, and stckoverflowexception is the jvm's way to tell you, you've reached that point.

I cant see the error.The last part of the error is at A.<init>(A.java:2)

Stultuske has explained this to you twice. I'll give it one more try.

line 7 A b=new A(); // creates a new instance of A
line 2 A a=new A(); // instance variable a is initialised as part of creating the new instance
line 2 A a=new A(); // new A() is executed to initialise variable a. It creates a new intance of A
line 2 A a=new A(); // instance variable a is initialised as part of creating the new instance
line 2 A a=new A(); // new A() is executed to initialise variable a It creates a new intance of A
line 2 A a=new A(); // instance variable a is initialised as part of creating the new instance
line 2 A a=new A(); // new A() is executed to initialise variable a It creates a new intance of A
etc etc until the JVM runs out of memory

Edited 5 Years Ago by JamesCherrill: n/a

This question has already been answered. Start a new discussion instead.