Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StackOverflowException

 
Shaveta Chawla
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Please tell me why theres stack overflow exception in the program below:

class A{
A a=new A();
int i=9;

}

public class finaltest {

public static void main(String[] args) {
A aa=new A();
A aa2=new A();
aa2=aa.a;
aa2.i=10;
System.out.println(aa2.i);

}
}


Thanks
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shaveta Chawla:
class A{
A a=new A();
int i=9;

}


I haven't tested this, but when you create an instance of A, one of its fields creates an instance of A. When you create an instance of A, one of its fields creates an instance of A. When you create an instance of A, one of its fields creates an instance of A. When you create an instance of A, one of its fields creates an instance of A. When you create an instance of A, one of its fields creates an instance of A. When you create an instance of A, one of its fields creates an instance of A.

etc.
 
saurav sarkar
Ranch Hand
Posts: 180
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the memory is unable to hold the number of objects
you are creating.You have put the JVM in a loop
by creating objects.

you are doing this

A aa=new A();

then again inside A you are doing A a new A();
 
Ashwin Sharma
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi....
if you want to use it make instance variable in class A static. Then the code will work.

class A{
A a=new A();
int i=9;
}
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you mean is that the code will no longer have a StackOverflow, but is that what the code is supposed to do?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic