Java continue outside of loop

How to Use Break, Continue, and Label in Loop in Java? Example

break and continue in Java are two essential keyword beginners needs to familiar while using loops ( for loop, while loop and do while loop). break statement in java is used to break the loop and transfers control to the line immediately outside of the loop while continue is used to escape current execution and transfers control back to the start of the loop. Both break and continue allows programmers to create sophisticated algorithms and looping constructs.

In this java tutorial, we will see examples of break and continue statements in Java and some important points related to breaking the loop using label and break statements. break keyword can also be used inside switch statements to break current choice and if not used it can cause fall-through on switch.

Well break is not alone on breaking switch case you can also sued throw keyword on switch case.

This Java tutorial is next in series of articles in looping like 4 ways to loop Map in Java and How to loop on ArrayList in Java. If you are new here and haven’t gone through those articles then you may find them useful.

break and continue statement in Java — example.

In this example we are calculating sum of odd numbers until number 5 appear, where we break the loop by using break statement. after calculating sum we also call continue which cause last line of loop to not execute. remember call to continue is inside if block which checks for odd numbers, so that line will appear in case of even number but not in case of odd number.

This example of break and continue shows that upon calling break , loop terminates and control goes to first line outside the loop while upon calling continue , loop doesn’t terminate but rest of execution doesn’t happen and loop continues from next iteration.

/**
* Simple Java program which demonstrate use of break and continue statements in Java
* In this example break is used to break loop and continue is used to escape current *iteration of loop once a condition is true.
* @author
*/

public class BreakContinueExample

public static void main ( String args [])

int [] numbers= new int [] < 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 >;

//calculate sum of all numbers till 5 appears
int sum = 0 ;
for ( int i= 0 ; i < numbers. length ; i++ )<
System. out . println ( «Executing for loop with iteration number: » + i ) ;
if ( i == 5 ) <
System. out . println ( «calling break statement to break for loop» ) ;
break ;
>
if ( i % 2 ! = 0 ) <
sum = sum + i ;
System. out . println ( «calling continue statement to start new iteration» ) ;
continue ;
>
System. out . println ( «Last line of loop, not executing for odd numbers due
to continue statement i: » + i ) ;
>
System. out . println ( «Outside of for loop, sum: » + sum ) ;
>
>

Output:
Executing for loop with iteration number: 0
Last line of loop, not executing for odd numbers due to continue statement i: 0
Executing for loop with iteration number: 1
calling continue statement to start new iteration
Executing for loop with iteration number: 2
Last line of loop, not executing for odd numbers due to continue statement i: 2
Executing for loop with iteration number: 3
calling continue statement to start new iteration
Executing for loop with iteration number: 4
Last line of loop, not executing for odd numbers due to continue statement i: 4
Executing for loop with iteration number: 5
calling break statement to break for loop
Outside of for loop, sum: 4

Читайте также:  Java create md5 hash

continue and break examples with label in Java

You can use labels with break and continue . labels are where you can shift control from break and continue . by default break goes outside of loop but if you more than one loop you can use the break statement to break a specific loop by providing labels.

The same is true for continue . if you are working on nested loops labels gives more control to break and continue . In the following the example of break and continue with labels. we have a nested loop and we have created two labels OUTER and INNER.

OUTER label is for outer loop and INNER label is for inner loop. we are iterating through array and print value of odd number from outer loop and then use continue statement, which ignores execution of inner loop. if its even number than inner loop executes and breaks as soon as it prints the number.

/**
* Simple Java program which demonstrate use of break and continue statements in Java
* with lables, break and continue can be used alongside label and loop.
*
* @author Javin
*/

public class BreakContinueWithLabel

public static void main ( String args [])

int [] numbers= new int [] < 100 , 18 , 21 , 30 >;

//Outer loop checks if number is multiple of 2
OUTER: //outer label
for ( int i = 0 ; i < numbers. length ; i++ )<
if ( i % 2 == 0 ) <
System. out . println ( «Odd number: » + i + «, continue from OUTER label» ) ;
continue OUTER ;
>

INNER:
for ( int j = 0 ; j < numbers. length ; j++ )<
System. out . println ( «Even number: » + i + «, break from INNER label» ) ;
break INNER ;
>
>

Output:
Odd number: 0 , continue from OUTER label
Even number: 1 , break from INNER label
Odd number: 2 , continue from OUTER label
Even number: 3 , break from INNER label

As shown in the above example of break and continue with labels, It provides a lot of conveniences to break and continue in case of a nested loop.

Important point about the break and continue in Java

1. break keyword transfers control to next statement outside loop while continue keyword transfers control to the beginning of loop, ignoring rest of lines in loop.

3. an optional label can be provided after break and continue which cause to apply break and continue on specified loop.

That’s all on break and continue statement in Java. break and continue allows programmer to control flow of execution in loops. We have also seen example of break and continue with and without labels , which allows you to write more sophisticated looping construct in java.

Источник

Branching Statements

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, as shown in the following BreakDemo program:

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; > > if (foundIt) < System.out.println("Found " + searchfor + " at index " + i); >else < System.out.println(searchfor + " not in the array"); >> >

This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop. This program’s output is:

Читайте также:  Vs code wsl python

An unlabeled break statement terminates the innermost switch , for , while , or do-while statement, but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo , is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled «search»):

class BreakWithLabelDemo < public static void main(String[] args) < int[][] arrayOfInts = < < 32, 87, 3, 589 >, < 12, 1076, 2000, 8 >, < 622, 127, 77, 955 >>; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) < for (j = 0; j < arrayOfInts[i].length; j++) < if (arrayOfInts[i][j] == searchfor) < foundIt = true; break search; >> > if (foundIt) < System.out.println("Found " + searchfor + " at " + i + ", " + j); >else < System.out.println(searchfor + " not in the array"); >> >

This is the output of the program.

The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

The continue Statement

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. The following program, ContinueDemo , steps through a String , counting the occurrences of the letter «p». If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a «p», the program increments the letter count.

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; // process p's numPs++; >System.out.println("Found " + numPs + " p's in the string."); > >

Here is the output of this program:

To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p’s instead of 9.

A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo , uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program, ContinueWithLabelDemo , uses the labeled form of continue to skip an iteration in the outer loop.

class ContinueWithLabelDemo < public static void main(String[] args) < String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i > foundIt = true; break test; > System.out.println(foundIt ? "Found it" : "Didn't find it"); > >

Here is the output from this program.

The return Statement

The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn’t. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.

Читайте также:  Add colour to html text

The data type of the returned value must match the type of the method’s declared return value. When a method is declared void , use the form of return that doesn’t return a value.

The Classes and Objects lesson will cover everything you need to know about writing methods.

Источник

Java continue statement

Java continue statement

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java continue statement is used to skip the current iteration of a loop. Continue statement in java can be used with for , while and do-while loop.

Java continue statement

When continue statement is used in a nested loop, it only skips the current execution of the inner loop. Java continue statement can be used with label to skip the current iteration of the outer loop too. Let’s have a look at some continue java statement examples.

Java continue for loop

Let’s say we have an array of integers and we want to process only even numbers, here we can use continue loop to skip the processing of odd numbers.

package com.journaldev.java; public class JavaContinueForLoop < public static void main(String[] args) < int[] intArray = < 1, 2, 3, 4, 5, 6, 7 >; // we want to process only even entries for (int i : intArray) < if (i % 2 != 0) continue; System.out.println("Processing entry " + i); >> > 

java continue statement, java continue for loop

Java continue while loop

Let’s say we have an array and we want to process only index numbers divided by 3. We can use java continue statement here with while loop.

package com.journaldev.java; public class JavaContinueWhileLoop < public static void main(String[] args) < int[] intArray = < 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 >; int i = 0; while (i < 10) < if (i % 3 != 0) < i++; continue; >System.out.println("Processing Entry " + intArray[i]); i++; > > > 

java while loop continue

Java continue do-while loop

We can easily replace above while loop code with do-while loop as below. Result and effect of continue statement will be same as above image.

do < if (i % 3 != 0) < i++; continue; >System.out.println("Processing Entry " + intArray[i]); i++; > while (i < 10); 

Java continue label

Let’s have a look at java continue label example to skip the outer loop processing. We will use two dimensional array in this example and process an element only if all the elements are positive numbers.

package com.journaldev.java; import java.util.Arrays; public class JavaContinueLabel < public static void main(String[] args) < int[][] intArr = < < 1, -2, 3 >, < 0, 3 >, < 1, 2, 5 >, < 9, 2, 5 >>; process: for (int i = 0; i < intArr.length; i++) < boolean allPositive = true; for (int j = 0; j < intArr[i].length; j++) < if (intArr[i][j] < 0) < allPositive = false; continue process; >> if (allPositive) < // process the array System.out.println("Processing the array of all positive ints. " + Arrays.toString(intArr[i])); >allPositive = true; > > > 

java continue label

Java continue important points

  1. For simple cases, continue statement can be easily replaced with if-else conditions but when we have multiple if-else conditions then using continue statement makes our code more readable.
  2. continue statement comes handy incase of nested loops and to skip a particular record from processing.

I have made a short video explaining java continue statement in detail, you should watch it below. https://www.youtube.com/watch?v=udqWkqhc2kw Reference: Oracle Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью