Quantcast
Channel: flounderCode()
Viewing all articles
Browse latest Browse all 10

Java break Statement

$
0
0

This is a quick detail of the break statement in JAVA that I picked up earlier today while working on another topic. The break statement will terminate a loop when an action is completed. The control flow then transfers to the statement immediately following the terminated statement. See example and comments below:

//BTG 2.11.14
/*
 * This is a simple program that demonstrates a break statement.  If you run the below code the 
 * result is: Found 12 at index 4.  If you remove the break the result is: Found 12 at index 10.
 * This clearly demonstrates the power of the break statement.
 */
public class breakDemo{
    public static void main (String[] args){
        
        int[] arrayOfInts = {32, 87, 3, 589, 12, 1076, 2000, 8, 622, 12};
        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+ " is not in the array.");
    }
}


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images