Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this method print 4?
    primarykey
    data
    text
    <p>I was wondering what happens when you try to catch an StackOverflowError and came up with the following method:</p> <pre><code>class RandomNumberGenerator { static int cnt = 0; public static void main(String[] args) { try { main(args); } catch (StackOverflowError ignore) { System.out.println(cnt++); } } } </code></pre> <p>Now my question:</p> <p>Why does this method print '4'?</p> <p>I thought maybe it was because <code>System.out.println()</code> needs 3 segments on the call stack, but I don't know where the number 3 comes from. When you look at the source code (and bytecode) of <code>System.out.println()</code>, it normally would lead to far more method invocations than 3 (so 3 segments on the call stack would not be sufficient). If it's because of optimizations the Hotspot VM applies (method inlining), I wonder if the result would be different on another VM.</p> <p><b>Edit</b>:</p> <p>As the output seems to be highly JVM specific, I get the result 4 using<br> Java(TM) SE Runtime Environment (build 1.6.0_41-b02)<br> Java HotSpot(TM) 64-Bit Server VM (build 20.14-b01, mixed mode)</p> <p><br></p> <p><b> Explanation why I think this question is different from <a href="https://stackoverflow.com/questions/15083318/understanding-java-stack">Understanding the Java stack</a>: </b></p> <p>My question is not about why there is a cnt > 0 (obviously because <code>System.out.println()</code> requires stack size and throws another <code>StackOverflowError</code> before something gets printed), but why it has the particular value of 4, respectively 0,3,8,55 or something else on other systems.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload