[java] Breaking out of a for loop in Java

In my code I have a for loop that iterates through a method of code until it meets the for condition.

Is there anyway to break out of this for loop?

So if we look at the code below, what if we want to break out of this for loop when we get to "15"?

public class Test {

   public static void main(String args[]) {

      for(int x = 10; x < 20; x = x+1) {
         System.out.print("value of x : " + x );
         System.out.print("\n");
      }
   }
}

Outputs:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

I've tried the following to no avail:

public class Test {

   public static void main(String args[]) {
      boolean breakLoop = false;
      while (!breakLoop) {
          for(int x = 10; x < 20; x = x+1) {
             System.out.print("value of x : " + x );
             System.out.print("\n");
          if (x = 15) {
              breakLoop = true;
          }
          }
      }
   }
}

And I've tried a loop:

public class Test {

   public static void main(String args[]) {
      breakLoop:
          for(int x = 10; x < 20; x = x+1) {
             System.out.print("value of x : " + x );
             System.out.print("\n");
             if (x = 15) {
                 break breakLoop;
             }
      }
   }
}

The only way I can achieve what I want to is by breaking out of a for loop, I cannot subsitute it for a while, do, if etc statement.

Edit:

This was provided only as an example, this isn't the code I'm trying to get it implemented into. I have now solved the problem by placing multiple IF statements after where each loop initilizes. Before it would onlu jump out of one part of the loop due to lack of breaks;

This question is related to java loops for-loop break

The answer is


You can use:

for (int x = 0; x < 10; x++) {
  if (x == 5) { // If x is 5, then break it.
    break;
  }
}

How about

for (int k = 0; k < 10; k = k + 2) {
    if (k == 2) {
        break;
    }

    System.out.println(k);
}

The other way is a labelled loop

myloop:  for (int i=0; i < 5; i++) {

              for (int j=0; j < 5; j++) {

                if (i * j > 6) {
                  System.out.println("Breaking");
                  break myloop;
                }

                System.out.println(i + " " + j);
              }
          }

For an even better explanation you can check here


If for some reason you don't want to use the break instruction (if you think it will disrupt your reading flow next time you will read your programm, for example), you can try the following :

boolean test = true;
for (int i = 0; i < 1220 && test; i++) {
    System.out.println(i);
    if (i == 20) {
        test = false;
    }
 }

The second arg of a for loop is a boolean test. If the result of the test is true, the loop will stop. You can use more than just an simple math test if you like. Otherwise, a simple break will also do the trick, as others said :

for (int i = 0; i < 1220 ; i++) {
    System.out.println(i);
    if (i == 20) {
        break;
    }
 }

public class Test {

public static void main(String args[]) {

  for(int x = 10; x < 20; x = x+1) {
     if(x==15)
         break;
     System.out.print("value of x : " + x );
     System.out.print("\n");
  }
}
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to break

How to break a while loop from an if condition inside the while loop? illegal use of break statement; javascript How can I use break or continue within for loop in Twig template? break statement in "if else" - java Regarding Java switch statements - using return and omitting breaks in each case Is it bad practice to use break to exit a loop in Java? break/exit script Breaking out of a for loop in Java How to break out of while loop in Python? How to kill a while loop with a keystroke?