How to break out of a while loop in Java?

To break out of a while loop in Java, use the break statement.

Here's how you do it:

int i = 0;

while (true) {
  i++;

  if (i > 3) {
    break;
  }

  System.out.println(i);
}

// prints:
// 1
// 2
// 3