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

Two simpe methods calling each other not working as expected

 
Nitin Bhagwat
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was expecting following program to run until it was not intruppted by user. This program runs for some time and then stops on it'w own. Can you please help me to understand the concept behind this ?

public class tst
{
public static void main(String ara[])
{
looptst t = new looptst();
t.first();
}
}


class looptst
{

void first()
{
System.out.println("In the first class!!");
second();
}

void second()
{
System.out.println("In the second class!!");
first();
}
}
 
zmarak ahmad djan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
stack overflow
 
Nanda Kishore
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nitin, I tried on my system and it is running continuously!!
 
Sagar Kar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StackOverflowError is a JVM exception thrown when a stack overflow occurs because an application recurses too deeply.
 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's called mutual recursion. first() calls second() which calls first() which calls second() which calls first() ... and so on ad infinitum. Each one of these calls uses up a chunk of memory on the main thread's stack. Eventually the program uses up all the memory available to the stack and the JVM throws a java.lang.StackOverflowError.

Don't do it!

There are legitimate uses for mutual recursion, though I can't think of one off the top of my head, but you need a base condition to ensure that the recursion will stop naturally at some point, hopefully before the stack runs out!

Jules
 
Daniel Mayer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Julian Kennedy:
Each one of these calls uses up a chunk of memory on the main thread's stack.


This memory is used to remember the return address of the calling method, and to store local variables, btw.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic