Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You won't be able to exit only from an <code>if</code> condition using either <code>return</code> or <code>break</code>.</p> <p><code>return</code> is used when you need to return from a method after it's execution is finished/you don't want to execute the rest of the method code. So if you use <code>return</code>, then you will not only return from your <code>if</code> condition, but also from the whole method.</p> <p>consider the following method - </p> <pre><code>public void myMethod() { int i = 10; if(i==10) return; System.out.println("This will never be printed"); } </code></pre> <p>Here, using <code>return</code> causes to stop the execution of the whole method after line 3 and execution goes back to its caller. </p> <p><code>break</code> is used to break out from a <code>loop</code> or a <code>switch</code> statement. Consider this example - </p> <pre><code>int i; for(int j=0; j&lt;10; j++) { for(i=0; i&lt;10; i++) { if(i==0) break; // This break will cause the loop (innermost) to stop just after one iteration; } if(j==0) break; // and then this break will cause the outermost loop to stop. } switch(i) { case 0: break; // This break will cause execution to skip executing the second case statement case 1: System.out.println("This will also never be printed"); } </code></pre> <p>This type of <code>break</code> statement is known as <code>unlabeled break</code> statement. There is another form of break, which is called <code>labeled break</code>. Consider this example - </p> <pre><code>int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i &lt; arrayOfInts.length; i++) { for (j = 0; j &lt; arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } </code></pre> <p>This example uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search").</p> <p>You can learn more abour <code>break</code> and <code>return</code> statements from <a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html"><code>JavaDoc</code></a>.</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