title: Exiting a loop in Java
body: <p>I'm using Java but I guess this question applies to whatever language. I just want to ask whether it's better practice to exit a loop using a boolean which I toggle within the loop or to just use break;</p>
  
  <p>For example, I was just writing a method to get the valid moves for a Queen in chess.</p>
  
  <pre><code>private static final int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};
  
  public Vector&lt;Move&gt; getValidMoves() {
      Vector&lt;Move&gt; validMoves = new Vector&lt;Move&gt;();
  
      for (int i = 0; i &lt; DIRS.length; i++) {
          boolean stopped = false;
          int newX = x + DIRS[i][0];
          int newY = y + DIRS[i][1];
          while (!stopped &amp;&amp; newX &gt;= 0 &amp;&amp; newX &lt; 8 &amp;&amp; newY &gt;= 0 &amp;&amp; newY &lt; 8) {
              if (board[newX][newY] == null) {
                  validMoves.add(new Move(x, y, newX, newY));
                  newX += DIRS[i][0];
                  newY += DIRS[i][1];
              } else {
                  if (board[newX][newY].getColour() == colour) {
                      stopped = true;
                  } else {
                      validMoves.add(new Move(x, y, newX, newY));
                      stopped = true;
                  }
              }
          }
      }
  
      return validMoves;
  }
  </code></pre>
  
  <p>If I exit the while loop using break; instead of setting stopped to true like I do it's my understanding that it runs more efficiently but is not the greatest code style.</p>