aspose file tools*
The moose likes Java in General and the fly likes Two simpe methods calling each other not working as expected Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Two simpe methods calling each other not working as expected" Watch "Two simpe methods calling each other not working as expected" New topic
Author

Two simpe methods calling each other not working as expected

Nitin Bhagwat
Ranch Hand

Joined: Sep 09, 2004
Posts: 132
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();
}
}


"Imagination is more important than knowledge. Knowledge is limited. Imagination encircles the world."
zmarak ahmad djan
Greenhorn

Joined: Sep 02, 2004
Posts: 20
stack overflow


zmarak (publican)
Nanda Kishore
Greenhorn

Joined: Aug 17, 2003
Posts: 9
Nitin, I tried on my system and it is running continuously!!
Sagar Kar
Greenhorn

Joined: Sep 03, 2004
Posts: 25
StackOverflowError is a JVM exception thrown when a stack overflow occurs because an application recurses too deeply.


Warm regards,<br />Sagar Kar.<br />SCJP 1.4, SCBCD 1.3
Julian Kennedy
Ranch Hand

Joined: Aug 02, 2004
Posts: 823
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

Joined: Sep 09, 2004
Posts: 103
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Two simpe methods calling each other not working as expected