Jumping around - break, continue, return


Collapse Content

Code is usually executed linearly or in loops. However, sometimes you may want the program to jump to a different spot of code. This could create very confusing code if unrestricted, so Java limits jumping to special cases.

break

The previous node mentioned how the break keyword is used to exit from a switch statement. It can also be used to exit from any loop (for, while and do-while). When used in a loop, the program will break out of the loop and continue executing code from after the loop block. Here's a simple example:

for(int i=0; i<100; i=i+1) {
  if(i == 7){
    break;
  }
  System.out.println(i);
}
System.out.println("finished");

This code will output the following:

0
1
2
3
4
5
6
finished

When i equals 7, the program breaks out of the loop, so no further numbers get printed. This code is a simple demonstration of break, but would not make sense to use in practice, since the condition of the loop can just be changed to i<7 instead of i<100. break should instead be used when there's a special circumstance not covered by the main condition of a loop. For example, it could be used to find the position of a number in an array:

public static void findNum(int[] array, int num)
{
    int i;
    boolean isThere = false;

    for (i = 0; i < array.length; i=i+1) {
        if (array[i] == num) {
            isThere = true;
            break;
        }
    }

    if (isThere) {
        System.out.println(num + " is at index " + i);
    } else {
        System.out.println(num + " isn't in array");
    }
}

The above code goes through array and stops when it reaches num. It then prints out the location of num.

The following code calls the above method to find 30 in an array:

int[] ar = {0,10,20,30,40};
findNum(ar, 30);

It will output:

30 is at index 3

If it passed in a number not in the array:

 findNum(ar, 50);

it will output:

50 isn't in array

As long as num hasn't been found, the loop needs to finish searching through array. However, one the number is found, there's no reason to continue searching, so it makes sense to use break.

labels and nested loops

When break is used in nested loops, it will exit from the innermost loop. In some cases, you may wish to jump to the outside of an outer loop.

Extra - Breaking out of Specifc Loops

continue

On rare occasion, you may want to skip the current iteration through a loop without exiting the loop entirely. You can use continue to do this. Here's a simple example for printing numbers from 0 through 6, except 3:

for(int i=0; i<7; i=i+1) {
  if(i == 3){
    continue;
  }
  System.out.println(i);
}
System.out.println("finished");

This will output:

0
1
2
4
5
6
finished

When i was 3, the code reached continue, but it did not exit the loop like by break. Instead, it just skipped the remaining code in the current iteration of the loop (the print statement), and continued at the top of the loop with i as 4.

return

While break and continue aren't used that often, return is a fundamental part of programming. Methods that declare a return type need to always return a value of that type. When return is called, the program returns to the code that originally called the method.

public class Sample
{
   public static void main(String[] args)
    {
        int n2 = doubleNum(5);
        System.out.println(n2);        
    }

    public static int doubleNum(int num){
      return num * 2;
    }
}

When the main method runs in the above code:

  1. doubleNum is called and passed a 5.
  2. doubleNum returns 10
  3. The program returns to main and assigns 10 to n2
  4. The main method continues by printing out 10 and the program finishes running.

void return
Methods with a void return type will usually run through their whole block of code and then the program will return to the previous code. However, on occasion you may want to return nothing to end execution of the method and return immediately to the previous code. The above method findNum could be refactored to use return instead of break:

public static void findNum2(int[] array, int num)
{
    for (int i = 0; i < array.length; i++ ) {
        if (array[i] == num) {
            System.out.println(num + " is at index " + i);
            return;
        }
    }
    System.out.println(num + " not in array");
}

This method does the same thing as before, but with less code.

Challenge

In the game of OddCards, only the odd-valued cards count. Each hand of cards is worth the sum of the odd-valued cards. However, multiples of 3 are deadly! If you get a card that is odd and is a multiple of 3 you lose all your points and the hand is scored at 0.

You will be given an array cards that contains the integer values of a hand of cards. Write a method that returns the score of cards.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • The example doesn't work. Input 2 gives a sum of 22, so shouldn't go back to 0, input 4 sums to 4 and again shouldn't be zero'd.

  • @Shane, those hands contain odd multiples of 3, which cause the score to be 0. I added some explanation above.

  • How do I resolve this?

    for (int i=1; i<cards.length; i++) {
    if (i%2!==0 && i%3!==0) {
    System.out.println(sum +=i);
    }
    }
    }

  • is there any hint? I'm stuck :(

  • static int doStuff(int[] cards){
    for (int i=1; i<cards.length; i++) {
    if (i%3==0) {
    break;}
    if (i%2!==0 && i%3!==0) {
    System.out.println(sum +=i);
    }
    System.out.println("0")

  • When you get a multiple of 3 remember that the whole hand gets to 0 no matter the cards before or after. Use break in that case.

  • Why are there no awnsers anywere?

  • Here is the awnser i forgot sum=0; before the break. devil in the details i guess.
    my code

  • OK I'm lost here...

    I think, according to the instructions my code is right. See the expected output. I think theres a mistake!
    Input Correct Output Your Output
    1 2 6 7 8 0
    1 2 4 5 7 9 0 0
    2 4 8 11 13 24 24
    1 2 3 4 0 0

    cont...
  • OK never mind LOOOOLL

Contact Us
Sign in or email us at [email protected]