Codelearn14 Codelearn14 - 1 year ago 62
Java Question

How to break a while loop from an if condition inside the while loop?

I want to break a while loop of the format below which has an if statement. If that if statement is true, the while loop also must break. Any help would be appreciated.

while(something.hasnext()) {
do something...
if(contains something to process){
do something
break if condition and while loop

Answer Source

if is not a loop. Simply call break;.

Contrived example:

public static void main(String[] args) {
  int i = 0;
  while (i++ < 10) {
    if (i == 5) break;
  System.out.println(i); //prints 5

If you were actually using nested loops, you would be able to use labels.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download