This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Exception in thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Exception in thread "main" java.lang.StackOverflowError" Watch "Exception in thread "main" java.lang.StackOverflowError" New topic
Author

Exception in thread "main" java.lang.StackOverflowError

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
The below code gives me an error :


Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Your class Car has a number of Car objects as fields:

If you create a new Car object, it is going to initialize its fields, for example c1. But c1 is also a Car object that has three Car objects as fields. And each of those again have three Car objects as fields, etcetera ad infinitum. The JVM will recursively start creating all those Car objects until the stack overflows.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Sue Temple
Greenhorn

Joined: May 01, 2010
Posts: 19
It is because you are initializing the object within itself - when you create a car, it tries to create another car, that tries to create another car and goes into a recursive loop.

Move this code to to test()

Sue Temple
Greenhorn

Joined: May 01, 2010
Posts: 19
Sorry about a duplicate answer, but you just beat me there, Jesper - I did not see your post when until I hit submit!
jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
Thanks for your replies.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception in thread "main" java.lang.StackOverflowError
 
Similar Threads
help in garbage collection question
how many objects will be eligible for garbage collection
Number of Objects eligible for Garbage Collection
Please explain me this!
Objects available for GC..