Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

stack trace problem, need help understanding.

 
Carly Davis
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the code below cause the following error to be repeated when ran:

at Testing.<init><Testing.java:5>

class Testing {
Testing t = new Testing();

public static void main(String [] args) {
Testing t2 = new Testing();
}
}

Thanks so much for your help!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

The problem is infinite recursion, which will probably lead to an out of memory exception.

The way you've written this, every instance of Testing has its own instance of Testing. So when you try to create an instance of Testing, that instance has to have its own instance of Testing, and in turn that instance has to have its own instance, and that instance has to have its own instance, and...
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Pepper Jack," please check your private messages by clicking on My Private Messages. Thanks!
 
Carly Davis
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much, that makes sense.

Carly, Previously "Pepper Jack"...I was eating pj cheese when I filled out my profile
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Carly Davis:
...I was eating pj cheese when I filled out my profile

Thanks for your prompt attention! I hope you find the ranch helpful!
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by marc weber:
The problem is infinite recursion, which will probably lead to an out of memory exception.


Two small corrections:

- it's an OutOfMemory*Error*, and
- in my experience, it will more likely lead to a StackOverflowError.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic