This example shows how to use the break statement in Java programming. Break itself a keyword that can be used within a block like for, while, do-while or switch statements. The significance of the break statement is to terminate the current loop and exit the block. It is mostly useful in the loops while we need to come out of the loop when the condition satisfies.
The below example lists the values from an ArrayList and terminates the loop once the “if” condition returns “true”.
package javabeat.net.core; import java.util.ArrayList; /** * Break statement example * @author krishna * */ public class BreakExample { public static void main(String args[]){ ArrayList<String> days = new ArrayList<String>(); days.add("Monday"); days.add("Tuesday"); days.add("Wednesday"); days.add("Thursday"); days.add("Friday"); days.add("Saturday"); days.add("Sunday"); for (String str : days){ System.out.println("Day : " + str ); if (str.equals("Friday")){ System.out.println("Last working day of week. Hurry!!!"); break; } } } }
Output
Day : Monday Day : Tuesday Day : Wednesday Day : Thursday Day : Friday Last working day of week. Hurry!!!