Move control in Java: break, continue, return

Java uses break, continue, and return statements to move control of the program.

break

There are three types of break syntax.

  • When escaping from switch syntax
  • When escaping from the loop
  • When used in an improved form of a goto syntax
class ForBreak {
	public static void main(String args[]) {
		for(int i=0; i<100; i++) {
			if(i==10) break;
			System.out.println(i + "Welcome to the world of Java!");
		}
		System.out.println("The for syntax was aborted by break.");
	}
}
break Basic example 1
class WhileBreak {
	public static void main(String args[]) {
		int i = 0;
		while(i<100) {
			if(i==10) break;
			System.out.println(i + "Welcome to the world of Java!");
			i++;
		}
		System.out.println("The while syntax was aborted by break.");
	}
}
break Basic example 2
class NestedForBreak {
	public static void main(String args[]) {
		int i, j;
		for(i=1; i<10; i++) {
			for(j=1; j<i; j++) {
				if(j>6) break; //Exclusion of only nested loops
				System.out.print(" * ");
			}
			System.out.println();
		}
	}
}
break Basic example 3
class BreakTest {
	public static void main(String args[]) {
		boolean t = true;
		first: {
			second: {
				third: {
					System.out.println("third block 'break' sentence before");
					if(t) break second; //Move control out of second block
					System.out.println("After the third block 'break' sentence");
				}
				System.out.println("second block sentence");
			}
			System.out.println("first block sentence");
		}
	}
}
break Basic example 4
//An example of an error
class BreakErr {
	public static void main(String args[]) {
		one: for(int i=0; i<3; i++) {
			System.out.print("Pass " + i + ": ");
		}

		for(int j=0; j<100; j++) {
			if(j == 10) break one; //An error occurs because it is not nested
			System.out.print(j + " ") ;
		}
	}
}
break Basic example 5

continue

continue sends control to the beginning of the loop at a specific point in the loop.

class ContinueTest {
	public static void main(String args[]) {
		for(int i=0; i<10; i++) {
			if(1%2 == 0) continue;
			System.out.println(i + "Welcome to the world of Java!");
		}
	}
}
continue Basic example 1
class ContinueLabelTest {
	public static void main(String args[]) {
		outer: for(int i=0; i<10; i++) {
			for(int j=0; j<10; j++) {
				if(j > i) {
					system.out.println();
					continue outer; //Move control to the beginning of the for block specified by outer
				}
				System.out.print(" " + (i*j));
			}
		}
	}
}
continue Basic example 2

return

return returns control to where the method was called.

class Return {
	public static void main(String args[]) {
		boolean t = true;
		System.out.println("Explicitly explained Java!");
		if(t) return;

		//Not running
		System.out.println("Let's learn Java.");
	}
}
return Basic example

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post