Can anybody explain what is the differences between two methods ?
method1
public void run(){
run();
}
method2
public void run(){
while(true){
}
}
Can anybody explain what is the differences between two methods ?
method1
public void run(){
run();
}
method2
public void run(){
while(true){
}
}
Example 1 is a method that never stops calling itself. Each time the method is called, a new frame is added to the callstack until, I think, there is a StackOverflowError.
Example 2 is an infinite loop. The method is added to the callstack only once.
Well, the recursive one will crash eventually. When using recursion you can only go a certain amount of levels before your program runs out of size to plac the method.
using a while true loop wihout any other code should run forever, because there are no more calls to another method, you're not doing anything with the stack anymore.
recursion calls the same method over and over again, which requires "space" to put the method ( like a pile of methods ), once the pile is too large, your program will quit. Using recursion has some advantages, but more often than not a loop is more suitable.
(even a while true loop you can terminate with 'break')
Generally each thread in Java has something called call stack. Each method execution goes into the stack, if one method executes another and then another you end up having few methods on call stack.
RandomObject.method1().method2().method3()
Will give you stack of:
method3()
method2()
method1()
The problem is that stack has limited space, and recursion will quickly fill it up giving you nasty StackOverFlow Exception.
In your case it would look like
run().run().run() (..)
So stack would look:
(...)
run()
run()
run()
The second option would have only one method on call stack and it would loop infinitly without crashing..
1st method will be called Recursively
2nd Method will be called one type but it will be stuck inside while loop for infinite times..it won't come out from the loop.