Mushfiq Mammadov wrote:I think this loop throws StackOverflowError when we run code. But it doesn't happen
That's indeed not true! Not every endless loop will result in a
StackOverflowError being thrown. A stack overflow occurs because an application recurses too deeply (meaning, too many methods on the call stack). But in this case the loop only prints something to the console. So on the call stack you only have 2 methods:
main() and
test(). Then you enter the loop and a 3rd method is added
println(). When this method is finished, it's removed from the stack. On the next iteration, the
println() method is added again and when finished, also removed again. On the next iteration, again the same story. So at most you'll have 3 methods on the call stack which is not enough to have an overflow.
You can very easily adjust the code a little bit to have a stack overflow (by adding just 1 line of code). So let's see if you can figure out which change will result in a
StackOverflowError being thrown.