5. Loops
5.1. while
1var n = 0;
2
3while (n < 10) {
4 System.out.println(n);
5 n++;
6}
5.2. do-while
1var n = 0;
2
3do {
4 System.out.println(n);
5 n++;
6} while (n < 10);
5.3. for
1var names = new String[] { "john", "jane", "joe", "jackson" };
2
3for (int i = 0; i < names.length; i++) {
4 System.out.println(names[i]);
5}
5.4. for-each
1var numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
2var sum = 0;
3
4for (int x : numbers) {
5 sum += x;
6}
5.5. Jump statements
5.5.1. break
1var numbers = new int[] { 0, 1, 2, 3, 4, 5 };
2
3for (int i = 0; i < numbers.length; i++) {
4 if (numbers[i] == 3) {
5 System.out.println("found 3 at index " + i);
6 break;
7 }
8}
1var matrix = new int[][] { {0, 1}, {2, 3}, {4, 5} };
2
3rowIter: for (int i = 0; i < matrix.length; i++) {
4 for (int j = 0; j < matrix[i].length; j++) {
5 if (matrix[i][j] == 3) {
6 System.out.println("found 3 at i = " + i + ", j = " + j);
7 break rowIter;
8 }
9 }
10}
5.5.2. continue
1var numbers = new int[] { 0, 1, 2, 3, 4, 5 };
2
3for (int i = 0; i < numbers.length; i++) {
4 if (numbers[i] % 2 == 0) {
5 continue;
6 }
7 System.out.println("found odd number " + numbers[i] + " at index " + i);
8}
1var matrix = new int[][] { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} };
2
3rowIter: for (int i = 0; i < matrix.length; i++) {
4 for (int j = 0; j < matrix[i].length; j++) {
5 if (matrix[i][j] % 2 != 0) {
6 System.out.println("found odd number " + matrix[i][j] + " at i = " + i + ", j = " + j);
7 continue rowIter;
8 }
9 }
10}