Java - Use break statement to exit a while-loop

Introduction

A break statement can exit the while-loop statement.

Demo

public class Main {
  public static void main(String[] args) {
    int i = 1;/*from   w  ww  . j a  va 2  s. co  m*/
    while (true) { // Cannot exit the loop from here
      if (i <= 10) {
        System.out.println(i);
        i++;
      } else {
        break; // Exit the loop
      }
    }

  }
}

Result

Related Topic