Difference between break and continue statement

JavaBreakContinue

Java Problem Overview


Can anyone tell me the difference between break and continue statements?

Java Solutions


Solution 1 - Java

break leaves a loop, continue jumps to the next iteration.

Solution 2 - Java

See Branching Statements for more details and code samples:

###break

> The break statement has two forms: labeled and unlabeled. You saw the > unlabeled form in the previous discussion of the switch statement. You > can also use an unlabeled break to terminate a for, while, or do-while > loop [...] > > An unlabeled break statement terminates the innermost switch, for, > while, or do-while statement, but a labeled break terminates an outer > statement.

###continue

> The continue statement skips the current iteration of a for, while , > or do-while loop. The unlabeled form skips to the end of the innermost > loop's body and evaluates the boolean expression that controls the > loop. [...] > > A labeled continue statement skips the current iteration of an outer loop marked with the given label.

Solution 3 - Java

System.out.println ("starting loop:");
for (int n = 0; n < 7; ++n)
{
	System.out.println ("in loop: " + n);
	if (n == 2) {
		continue;
	}
	System.out.println ("	survived first guard");
	if (n == 4) {
		break;
	}
	System.out.println ("	survived second guard");
	// continue at head of loop
}
// break out of loop
System.out.println ("end of loop or exit via break");

This will lead to following output:

starting loop:
in loop: 0
	survived first guard
	survived second guard
in loop: 1
	survived first guard
	survived second guard
in loop: 2
in loop: 3
	survived first guard
	survived second guard
in loop: 4
	survived first guard
end of loop or exit via break

You can label a block, not only a for-loop, and then break/continue from a nested block to an outer one. In few cases this might be useful, but in general you'll try to avoid such code, except the logic of the program is much better to understand than in the following example:

first:
for (int i = 0; i < 4; ++i) 
{
	second:
	for (int j = 0; j < 4; ++j) 
	{
		third:
		for (int k = 0; k < 4; ++k) 
		{
			System.out.println ("inner start: i+j+k " + (i + j + k));
			if (i + j + k == 5)
				continue third;
			if (i + j + k == 7)
				continue second;
			if (i + j + k == 8)
				break second;
			if (i + j + k == 9)
				break first;
			System.out.println ("inner stop:  i+j+k " + (i + j + k));
		}
	}		
}

Because it's possible, it doesn't mean you should use it.

If you want to obfuscate your code in a funny way, you don't choose a meanigful name, but http: and follow it with a comment, which looks alien, like a webadress in the source-code:

http://stackoverflow.com/questions/462373
for (int i = 0; i < 4; ++i) 
{
     if (i == 2) 
         break http;

I guess this is from a Joshua Bloch quizzle. :)

Solution 4 - Java

Break leaves the loop completely and executes the statements after the loop. Whereas Continue leaves the current iteration and executes with the next value in the loop.

> This Code Explains Everything :

public static void main(String[] args) {
	for(int i=0;i<10;i++)
	{
		if (i==4)
		{
			break;
		}
		System.out.print(i+"\t");
		
	}
	System.out.println();
	for(int i=0;i<10;i++)
	{
		
		if (i==4)
		{
			continue;
		}
		System.out.print(i+"\t");
	}
}

Output:

0	1	2	3	
0	1	2	3	5	6	7	8	9

Solution 5 - Java

break completely exits the loop. continue skips the statements after the continue statement and keeps looping.

Solution 6 - Java

Break Statement

Sometimes it’s necessary to exit a loop before the loop has finished fully iterating over all the step values. For example, looping over a list of numbers until you find a number that satisfies a certain condition. Or looping over a stream of characters from a file until a certain character is read.

In the following example, we’re using a simple for loop to print out values from 0 to 9:

for(int i=0; i<10; i++) {
  System.out.println(i);
}

Output:

0
1
2
3
4
5
6
7
8
9

Now if we add a break statement when i==4, our code will break out of the loop once i equals 4. You can use the break statement to break out of for loops, while loops and do-while loops. The break statement will only break out of the current loop. In order to break out of an outer loop from a nested inner loop, you would need to use labels with the break statement.

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

Output:

0
1
2
3
4

Continue Statement

Java’s continue statement skips over the current iteration of a loop and goes directly to the next iteration. After calling the continue statement in a for loop, the loop execution will execute the step value and evaluate the boolean condition before proceeding with the next iteration. In the following example, we’re printing out all values from 0 to 9 in a loop but we skip over printing out 4.

for(int i=0; i<10; i++) {
  if(i==4) {
    continue;
  }
  System.out.println(i);
}

Output:

0
1
2
3
5 <---- SKIPPED OVER 4 and continued with next loop iteration
6
7
8
9

Loop Label - Break Statement You can use labels within nested loops by specifying where you want execution to continue after breaking out of an inner loop. Normally, the break statement will only break out of the innermost loop so when you want to break out of an outer loop, you can use labels to accomplish this, essentially doing something similar to a goto statement.

The following example uses 3 loops, all nested within each other. Since there’s no way completely break out of the outer most loop from inside the inner most loop, we can use the label “outer1” to accomplish this and specify the label next to the break statement.

outer1:
for(int i=0; i<5; i++) {
  for(int j=0; j<4; j++) {
    for(int k=0; k<2; k++) {
      System.out.println("[" + i + "][" + j + "][" + k + "]");
      if(j == 3) {
        break outer1;
      }
    }
  }
}

Output:

[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0]

Notice how the last line displayed is “0[0]” which is where j == 3 and that’s where we called “break outer1;” to break out of the outer most loop.

Loop Labels - Continue Statement

You can also use labels with the continue keyword to continue looping from a specific point. Taking the previous example and just changing one line to specify continue outer1; instead of break outer1; will cause the loop to continue looping from the outer1 label instead of breaking out of the loop. Note how each time continue outer1; is called, the code continues from the outer loop after incrementing the loop index i by 1.

outer1:
for(int i=0; i<5; i++) {
  for(int j=0; j<4; j++) {
    for(int k=0; k<2; k++) {
      System.out.println("[" + i + "][" + j + "][" + k + "]");
      if(j == 3) {
        continue outer1;
    }
  }
}

[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[1][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[1][0][1]
[1][1][0]
[1][1][1]
[1][2][0]
[1][2][1]
[1][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[2][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[2][0][1]
[2][1][0]
[2][1][1]
[2][2][0]
[2][2][1]
[2][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[3][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[3][0][1]
[3][1][0]
[3][1][1]
[3][2][0]
[3][2][1]
[3][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[4][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[4][0][1]
[4][1][0]
[4][1][1]
[4][2][0]
[4][2][1]
[4][3][0]

Source: Loops in Java – Ultimate Guide

Solution 7 - Java

A break statement results in the termination of the statement to which it applies (switch, for, do, or while).

A continue statement is used to end the current loop iteration and return control to the loop statement.

Solution 8 - Java

Excellent answer simple and accurate.

I would add a code sample.

C:\oreyes\samples\java\breakcontinue>type BreakContinue.java

    class BreakContinue {

        public static void main( String [] args ) {

               for( int i = 0 ; i < 10 ; i++ ) {

                     if( i % 2 == 0) { // if pair, will jump
                         continue; // don't go to "System.out.print" below.
                     }

                     System.out.println("The number is " + i );

                     if( i == 7 ) {
                         break; // will end the execution, 8,9 wont be processed
                      }

               }
        }

    }

C:\oreyes\samples\java\breakcontinue>java BreakContinue
The number is 1
The number is 3
The number is 5
The number is 7

Solution 9 - Java

continue skips the current executing loop and MOVES TO the next loop whereas break MOVES OUT of the loop and executes the next statement after the loop. I learned the difference using the following code. Check out the different outputs.Hope this helps.

public static void main(String[] args) {
	for(int i = 0; i < 5; i++){
		if (i == 3) {
			continue;
		}
		System.out.print(i);
	}
}//prints out 0124, continue moves to the next iteration skipping printing 3

public static void main(String[] args) {
	for(int i = 0; i < 5; i++){
		if (i == 3) {
			break;
		}
		System.out.print(i);
	}
}//prints out 012, break moves out of the loop hence doesnt print 3 and 4

Solution 10 - Java

Consider the following:

int n;
for(n = 0; n < 10; ++n) {
	break;
}
System.out.println(n);

break causes the loop to terminate and the value of n is 0.

int n;
for(n = 0; n < 10; ++n) {
	continue;
}
System.out.println(n);

continue causes the program counter to return to the first line of the loop (the condition is checked and the value of n is increment) and the final value of n is 10.

It should also be noted that break only terminates the execution of the loop it is within:

int m;
for(m = 0; m < 5; ++m)
{
    int n;
	for(n = 0; n < 5; ++n) {
		break;
	}
	System.out.println(n);
}
System.out.println(m);

Will output something to the effect of

0
0
0
0
0
5

Solution 11 - Java

The break statement breaks out of the loop (the next statement to be executed is the first one after the closing brace), while continue starts the loop over at the next iteration.

Solution 12 - Java

The break statement exists the current looping control structure and jumps behind it while the continue exits too but jumping back to the looping condition.

Solution 13 - Java

Simple Example:

break leaves the loop.

int m = 0;
for(int n = 0; n < 5; ++n){
  if(n == 2){
    break;
  }
  m++;
}

System.out.printl("m:"+m); // m:2

continue will go back to start loop.

int m = 0;
for(int n = 0; n < 5; ++n){
  if(n == 2){
    continue; // Go back to start and dont execute m++
  }
  m++;
}

System.out.printl("m:"+m); // m:4

Solution 14 - Java

To prevent anything from execution if a condition is met one should use the continue and to get out of the loop if a condition is met one should use the break.

For example in the below mentioned code.

 for(int i=0;i<5;i++){
        
        if(i==3){
     
           continue;
     
        }
       System.out.println(i);
     }

The above code will print the result : 0 1 2 4

NOw consider this code

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

            if(i==3){
         
                break;
        
            }
            System.out.println(i);
         }

This code will print 0 1 2

That is the basic difference in the continue and break.

Solution 15 - Java

here's the semantic of break:

int[] a = new int[] { 1, 3, 4, 6, 7, 9, 10 };
// find 9
for(int i = 0; i < a.Length; i++)
{
    if (a[i] == 9) 
        goto goBreak;

    Console.WriteLine(a[i].ToString());      
}
goBreak:;

here's the semantic of continue:

int[] a = new int[] { 1, 3, 4, 6, 7, 9, 10 };
// skip all odds
for(int i = 0; i < a.Length; i++)
{
    if (a[i] % 2 == 1) 
        goto goContinue;

    Console.WriteLine(a[i].ToString());      

goContinue:;
}

Solution 16 - Java

First,i think you should know that there are two types of break and continue in Java which are labeled break,unlabeled break,labeled continue and unlabeled continue.Now, i will talk about the difference between them.

class BreakDemo {
public static void main(String[] args) {

    int[] arrayOfInts = 
        { 32, 87, 3, 589,
          12, 1076, 2000,
          8, 622, 127 };
    int searchfor = 12;

    int i;
    boolean foundIt = false;

    for (i = 0; i < arrayOfInts.length; i++) {
        if (arrayOfInts[i] == searchfor) {
            foundIt = true;
            break;//this is an unlabeled break,an unlabeled break statement terminates the innermost switch,for,while,do-while statement.
        }
    }

    if (foundIt) {
        System.out.println("Found " + searchfor + " at index " + i);
    } else {
        System.out.println(searchfor + " not in the array");
    }
}

An unlabeled break statement terminates the innermost switch ,for ,while ,do-while statement.

public class BreakWithLabelDemo {
public static void main(String[] args) {
	search:
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 5; j++) {
			System.out.println(i + " - " + j);
			if (j == 3)
				break search;//this is an labeled break.To notice the lab which is search.
		}
	}
}

A labeled break terminates an outer statement.if you javac and java this demo,you will get:

0 - 0
0 - 1
0 - 2
0 - 3

class ContinueDemo {
public static void main(String[] args) {

    String searchMe = "peter piper picked a " + "peck of pickled peppers";
    int max = searchMe.length();
    int numPs = 0;

    for (int i = 0; i < max; i++) {
        // interested only in p's
        if (searchMe.charAt(i) != 'p')
            continue;//this is an unlabeled continue.

        // process p's
        numPs++;
    }
    System.out.println("Found " + numPs + " p's in the string.");
}

An unlabeled continue statement skips the current iteration of a for,while,do-while statement.

public class ContinueWithLabelDemo {
public static void main(String[] args) {
	search:
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 5; j++) {
			System.out.println(i + " - " + j);
			if (j == 3)
				continue search;//this is an labeled continue.Notice the lab which is search
		}
	}
}

A labeled continue statement skips the current iteration of an outer loop marked with the given lable,if you javac and java the demo,you will get:

0 - 0
0 - 1
0 - 2
0 - 3
1 - 0
1 - 1
1 - 2
1 - 3
2 - 0
2 - 1
2 - 2
2 - 3

if you have any question , you can see the Java tutorial of this:enter link description here

Solution 17 - Java

Simply put: break will terminate the current loop, and continue execution at the first line after the loop ends. continue jumps back to the loop condition and keeps running the loop.

Solution 18 - Java

for (int i = 1; i <= 3; i++) {
		if (i == 2) {
			
			continue;
		}
		System.out.print("[i:" + i + "]");

try this code in netbeans you'll understand the different between break and continue

for (int i = 1; i <= 3; i++) {
		if (i == 2) {
			
			break;
		}
		System.out.print("[i:" + i + "]");

Solution 19 - Java

Simple program to understand difference between continue and break

When continue is used

    public static void main(String[] args) {
    System.out.println("HelloWorld");
    for (int i = 0; i < 5; i++){
        System.out.println("Start For loop i = " + i);
        if(i==2){
            System.out.println("Inside if Statement for i = "+i);
           continue;
        }
        System.out.println("End For loop i = " + i);
    }
    System.out.println("Completely out of For loop");
}


OutPut:
HelloWorld
Start For loop i = 0
End For loop i = 0
Start For loop i = 1
End For loop i = 1
Start For loop i = 2
Inside if Statement for i = 2
Start For loop i = 3
End For loop i = 3
Start For loop i = 4
End For loop i = 4
Completely out of For loop

When break is used

public static void main(String[] args) {
    System.out.println("HelloWorld");
    for (int i = 0; i < 5; i++){
        System.out.println("Start For loop i = " + i);
        if(i==2){
            System.out.println("Inside if Statement for i = "+i);
           break;
        }
        System.out.println("End For loop i = " + i);
    }
    System.out.println("Completely out of For loop");
}

Output:
HelloWorld
Start For loop i = 0
End For loop i = 0
Start For loop i = 1
End For loop i = 1
Start For loop i = 2
Inside if Statement for i = 2
Completely out of For loop

Solution 20 - Java

Continue Statment stop the itration and start next ittration Ex:

System.out.println("continue when i is 2:");
	for (int i = 1; i <= 3; i++) {
		if (i == 2) {
			System.out.print("[continue]");
			continue;
		}
		System.out.print("[i:" + i + "]");
	}

and Break Statment stop the loop or Exit from the loop

Solution 21 - Java

so you are inside a for or while loop. Using break; will put you outside of the loop. As in, it will end. Continue; will tell it to run the next iteration.

No point in using continue in if statement, but break; is useful. In switch...case, always use break; to end a case, so it does not executes another case.

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
QuestionDonXView Question on Stackoverflow
Solution 1 - JavaXn0vv3rView Answer on Stackoverflow
Solution 2 - JavaJayView Answer on Stackoverflow
Solution 3 - Javauser unknownView Answer on Stackoverflow
Solution 4 - JavaGeorge RosarioView Answer on Stackoverflow
Solution 5 - JavajsightView Answer on Stackoverflow
Solution 6 - JavagomishaView Answer on Stackoverflow
Solution 7 - JavaWarriorView Answer on Stackoverflow
Solution 8 - JavaOscarRyzView Answer on Stackoverflow
Solution 9 - JavaAbdullah KhanView Answer on Stackoverflow
Solution 10 - JavaKevin LoneyView Answer on Stackoverflow
Solution 11 - JavaGraeme PerrowView Answer on Stackoverflow
Solution 12 - JavaGumboView Answer on Stackoverflow
Solution 13 - JavaMarkus LausbergView Answer on Stackoverflow
Solution 14 - JavaNavankur ChauhanView Answer on Stackoverflow
Solution 15 - JavaMichael BuenView Answer on Stackoverflow
Solution 16 - JavathinkinjavaView Answer on Stackoverflow
Solution 17 - JavaElectrons_AhoyView Answer on Stackoverflow
Solution 18 - JavaReemView Answer on Stackoverflow
Solution 19 - JavacoderView Answer on Stackoverflow
Solution 20 - JavaNull Pointer ExceptionView Answer on Stackoverflow
Solution 21 - JavaPerimeView Answer on Stackoverflow