I have seen loops like for ( ; ; )
and while (true )
.
Many programs use this technique to run loops infinitely. Is it possible to use recursion to apply the same technique?
I have seen loops like for ( ; ; )
and while (true )
.
Many programs use this technique to run loops infinitely. Is it possible to use recursion to apply the same technique?
No. Every level of recursion will place a new frame onto the stack for internal use and local variables.
With every level of depth added, you will eventually reach the end of a finite amount of memory dedicated for this stack. There is a shadow zone reserved for the last frame and any C++ area, so hitting that is enough for the stack to overflow.
Java methods generate code that checks that stack space is available a fixed distance towards the end of the stack so that the native code can be called without exceeding the stack space. This distance towards the end of the stack is called “Shadow Pages.” The size of the shadow pages is between 3 and 20 pages, depending on the platform. This distance is tunable, so that applications with native code needing more than the default distance can increase the shadow page size.
This is used in case you enter native code, which cannot detect end-of-stack reliably. If you do not have enough space on the stack for any recursion or calls made in native code, a true hard stack overflow could occur with nasty consequences.
Note that Java does not perform tail recursion optimization, so recursion is not turned into iteration by the compiler.
Every time a function calls itself, this consumes stack space. Since stack is a finite resource, the program will eventually run out of stack space and be killed.
That said, it would be possible to create an infinite loop on a JVM that supported tail call optimization.
However, I am not aware of any such JVM. For a detailed discussion, see Does the JVM prevent tail call optimizations?
"If there is a chance to run a program infinitely using recursion in java?"
-No. But it may appear that some method or code snippets are trying to run infinitely but eventually they will error out. The main method below calling itself infinitely. You may think you are doing something infinitely but a certain amount of stack depending on the platform will eventually run out and jvm will throw the stack overflow error. So, technically no, you cannot.
public static void main(String... args){
main(args);
}
Above is an example of bad recursion that will eventually lead to stack overflow error.
Edited per confusion.