Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There isn't any direct equivalent to the <code>goto</code> concept in Java. There are a few constructs that allow you to do <em>some</em> of the things you can do with a classic <code>goto</code>.</p> <ul> <li>The <code>break</code> and <code>continue</code> statements allow you to jump out of a block in a loop or switch statement.</li> <li>A labeled statement and <code>break &lt;label&gt;</code> allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block).</li> <li>If you label a loop statement, you can <code>continue &lt;label&gt;</code> to continue with the next iteration of an outer loop from an inner loop.</li> <li>Throwing and catching exceptions allows you to (effectively) jump out of many levels of a method call. (However, exceptions are relatively expensive and are considered to be a bad way to do "ordinary" control flow<sup>1</sup>.)</li> <li>And of course, there is <code>return</code>.</li> </ul> <p>None of these Java constructs allow you to branch backwards or to a point in the code at the same level of nesting as the current statement. They all jump out one or more nesting (scope) levels and they all (apart from <code>continue</code>) jump downwards. This restriction helps to avoid the goto "spaghetti code" syndrome inherent in old BASIC, FORTRAN and COBOL code<sup>2</sup>.</p> <hr> <p><sup> 1- The most expensive part of exceptions is the actual creation of the exception object and its stacktrace. If you really, really need to use exception handling for "normal" flow control, you can either preallocate / reuse the exception object, or create a custom exception class that overrides the <code>fillInStackTrace()</code> method. The downside is that the exception's <code>printStackTrace()</code> methods won't give you useful information ... should you ever need to call them.</sup></p> <p><sup> 2 - The spaghetti code syndrome spawned the <a href="http://en.wikipedia.org/wiki/Structured_programming" rel="noreferrer">structured programming</a> approach, where you limited in your use of the available language constructs. This could be applied to <a href="http://en.wikipedia.org/wiki/BASIC" rel="noreferrer">BASIC</a>, <a href="http://en.wikipedia.org/wiki/Fortran" rel="noreferrer">Fortran</a> and <a href="http://en.wikipedia.org/wiki/COBOL" rel="noreferrer">COBOL</a>, but it required care and discipline. Getting rid of <code>goto</code> entirely was a pragmatically better solution. If you keep it in a language, there is always some clown who will abuse it.</sup></p>
 

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