break

It can be used in the following places.

  1. within the loops to come out of the loop.
  2. Inside switch statement to come out of the switch .

If we are using break any where else we will get a compile time error.
Example:

class Test {

	public static void main(String[] args) {
		int x = 0;
		if(x!=5)
		break;
		System.out.println("if");
	}
}
/*
Compile time error:
break outside switch or loop.
*/

continue

  1. we should use ‘continue’ only in the loops to skip current iteration & continue for the next iteration.
  2. If we are using ‘continue’ any where except loops we will get compile time error saying “continue outside of loop”.

Example:

class Test {

	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			if ((i % 2) == 0)
				continue;
			System.out.println(i);
		}
	}
}
/*
Output:
1
3
5
7
9
*/

labelled break

class Test {

	public static void main(String[] args) {
		boolean x = true;
		bl1: {
			bl2: {
				bl3: {
					System.out.println("block3");
					if (x)
						break bl2; // goto end of bl2
				}// end of bl3
				System.out.println("block2");
			}// end of bl2
			System.out.println("block1");
		}// end of bl1
		System.out.println("out of all blocks");
	}
}
/*
Output:
block3
block1
out of all blocks
*/

Labeled break and continue

In the case of nested loops .if we want to break or continue a particular loop then we should go for labeled break and continue.

class Test {

	public static void main(String[] args) {
		l1: for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				if (i == j)
					continue l1;//Replace with any transfer statements
				System.out.println(i + "---" + j);
			}
		}
	}
}

Output:

break    continue    break l1:    continue l1:
1---0    0---1       no output    1---0
2---0    0---2                    2---0 
2---1    1---0                    2---1
         1---2 
	 2---0
	 2---1	

Example:Fine the output of the following program?

class Test {

	public static void main(String[] args) {
		int x = 0;
		do {
			x++;
			System.out.println(x);
			if (++x > 5)
				continue;
			x++;
			System.out.println(x);
		} while (++x < 10);
	}
}
/*
Output:
1
3
5
8

*/