Java Branching Statements

Now that you understand the while and do-while statements from lesson 8.4, let’s move onto the next lesson on the Java Branching Statement.

The break, continue, and return statements comprise the branching statements in the Java programming language.

Break Statement

The break statement has two different types, labeled or unlabeled. The unlabeled form is the most common.

The following code sample defines an array of integers and it also defines a specific integer that is being searched for. The program loops through the array of integers comparing each to what we are looking for (25). Once a match is found, the break statement will force a drop out of the for loop.

int[] integerArray =  { 10, 15, 20, 25, 30, 35, 40, 45, 50 };
int lookingFor = 25;
boolean foundNumber = false;

for (int ctr = 0; ctr < integerArray.length; ctr++) {

     if (integerArrayctr] == lookingFor) {

         foundNumber = true;
         break;
     }
}


Continue Statement

The continue statement skips the current iteration of a for loop, while loop, or a do-while loop. The unlabeled continue is the most common to use. The unlabeled continue skips to the end of the innermost loop’s body and evaluates the boolean expression that controls the loop.

Let’s look at the sample code below. The purpose of the code is to count the number of times ‘a’ is found in the jcdTextString. If the letter is not an ‘a’, the program will jump back to the top of the for loop.

String jcdTextString = "Java Code Depot Contains Java Tutorials";
		
int strLength = jcdTextString.length();
int letterCount = 0;

for (int ctr = 0; ctr < strLength; ctr++) {
            
    if (jcdTextString.charAt(ctr) != 'a')
        continue;

    letterCount++;
}
        
System.out.println("Found Letter 'a' Times: " +letterCount);


Output

Found Letter 'a' times: 6


Return Statement

The final branching statements is the return statement. The return statement will exit from the current method. Once that happens, control flow returns to where the method was invoked. The return statement has two forms, one returns a value and the other does not.

This return statement will return some value from a method call.

return value;


This return statement will return empty from a method call.

return;


Now that your done with lesson 8.5, be sure to move onto the control flow knowledge check.


Add a Comment

Your email address will not be published. Required fields are marked *