-1

Can anybody explain what is the differences between two methods ?

method1

public void run(){
    run();
}

method2

public void run(){
   while(true){

   }    
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
Talha
  • 12,673
  • 5
  • 49
  • 68

4 Answers4

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.

Sankar V
  • 4,794
  • 3
  • 38
  • 56
W.K.S
  • 9,787
  • 15
  • 75
  • 122
  • 1
    In the first method StackOverflowError will occur – mahesh Apr 02 '14 at 07:42
  • Can you explain the difference between exception and error? – Thomas Uhrig Apr 02 '14 at 07:43
  • 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. http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html – W.K.S Apr 02 '14 at 07:46
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')

Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49
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..

Community
  • 1
  • 1
Taks
  • 2,033
  • 4
  • 18
  • 23
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.

Skabdus
  • 220
  • 3
  • 13