-1

Can anybody explain what is the differences between two methods ?

method1

public void run(){
    run();
}

method2

public void run(){
   while(true){

   }    
}
5

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

In the first method StackOverflowError will occur
Can you explain the difference between exception and error?
In Java, an Exception is something that the application might recover from. A developer should catch Exceptions. An Error is an irrecoverable situation and it should not be caught. docs.oracle.com/javase/7/docs/api/java/lang/Error.html
0

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')

Comments

0

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..

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.