• Post Reply Bookmark Topic Watch Topic
  • New Topic

What are StackOverflowErrors? When are they typically thrown?  RSS feed

 
Shridhar Raghavan
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi,
The above code throws a stackoverflowerror.

Have read a few posts that explained that stack errors are typically thrown due to an endless loop.

1. Any other nuances.

Also i had come across a question on a website which i am trying to trace back.

The code in the question was somewhat like below


The above code just a brief recollection.

2.But the question i had in mind is can using chained iterators on a collection lead to some sort of StackOverflow which the website said would happen.
 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can figure out for yourself when a stack overflow occurs, if you know what the stack is.

The stack is a piece of memory that your program uses to store all the local variables in a method. Every time you call a method, Java adds a so called "stack frame" to the stack, this frame holds the local variables for the method you just called. When the method is finished, that frame is removed from the stack again, revealing the stack frame belonging to the calling method, so that method can resume execution.

The stack overflows when it has no more space to add the next stack frame. This happens when a method calls another method, and that method calls another method, etc; until there is no more memory. You will usually encounter this problem when you make a recursive method call.

In your first program, you can see that the main function calls doSomething(String) at line 12. This method in turn calls the main function, at line 34. This is a never ending loop, which keeps pushing frames on the stack, but the methods never get a chance to finish.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!