Breaking out of a for loop in Java

JavaLoopsFor LoopBreak

Java Problem Overview


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;

Java Solutions


Solution 1 - Java

break; is what you need to break out of any looping statement like for, while or do-while.

In your case, its going to be like this:-

for(int x = 10; x < 20; x++) {
         // The below condition can be present before or after your sysouts, depending on your needs.
         if(x == 15){
             break; // A unlabeled break is enough. You don't need a labeled break here.
         }
         System.out.print("value of x : " + x );
         System.out.print("\n");
}

Solution 2 - Java

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;
    }
 }

Solution 3 - Java

You can use:

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

Solution 4 - Java

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

Solution 5 - Java

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");
  }
}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsilverzxView Question on Stackoverflow
Solution 1 - JavaRahulView Answer on Stackoverflow
Solution 2 - Javauser2145100View Answer on Stackoverflow
Solution 3 - JavaJoaaoVeronaView Answer on Stackoverflow
Solution 4 - JavaHussain Akhtar Wahid 'Ghouri'View Answer on Stackoverflow
Solution 5 - JavaAchintya JhaView Answer on Stackoverflow