The break and continue statements?

Several programming languages including Visual Basic support the goto statement. This allows code to jump to any other location in a program. Although this seems useful, indiscriminate use of goto statements can result in hard to maintain spaghetti code. The name spaghetti code comes from the idea of spaghetti pasta on a plate where you cannot see where one strand begins and another ends.

The designers of Java decided that they agreed with programming guru Edsger Dijkstra who wrote a famous article titled "Goto considered harmful". it has fallen out of use and considered bad programming style. The goto statement is sometimes known as an "unconditional jump", ie it is possible to write code that jumps from one part of a program to another without even performing a test. There are situations when it would be useful and to help in those situations Java offers the labelled and unlabelled versions of the break and continue keywords.

The following code demonstrates how these two statements work.

public class BreakContinue{
public static void main(String argv[]){
	System.out.println("Break");
	for(int i=1; i < 4; i++){
		System.out.println(i);
			if(i > 1) break;
		}
	System.out.println("Continue");
	for(int i=1; i < 4; i++){
		System.out.println(i);	
			if(i > 1) continue;
		}
	}
}

This code will output Break 1 2 followed by Continue 123. This is because the break continue entirely stops the execution of the for loop whereas the continue statement only stops the current iteration.

Last modified: Sunday, 20 September 2015, 07:21 PM