Loops

 
/** 
 * The 'for' is used when you know how many loops.
 * The 'enchanced-for' is used whne index is not needed.
 * The 'forEach' loops over a Collection, it is ofthen used with
 * lambdas or  method reference
 */

package com.minte9.basics.loops;
import java.util.Arrays;
import java.util.List;

public class Loops {            
    public static void main(String[] args) {
        
        System.out.print("\nFor loop: ");

        for (int i=0; i<3; i++) {
            System.out.print(i);
        }

        System.out.print("\nEnhanced for: ");

        int[] nums = {0, 1, 2};
        for (int no : nums) {
            System.out.print(no);
        }

        System.out.print("\nforEach with lambdas: ");

        List<Integer> A = Arrays.asList(0, 1, 2);
        A.forEach(x -> System.out.print(x));

        System.out.print("\nforEach with method reference: ");

        List<Integer> B = Arrays.asList(0, 1, 2);
        B.forEach(System.out::print);
    }
}

/**
    For loop: 012
    Enhanced for: 012
    forEach with lambdas: 012
    forEach with method reference: 012
 */

Breaks

 
/**
 * The 'break' statement is used to exit from a loop.
 * For multiple loops we use labels.
 */

package com.minte9.basics.loops;

public class Breaks {            
    public static void main(String[] args) {
        
        int[][] numbers = { 
            {1,2,3}, 
            {4,5,6}, 
            {7,8,9},
        };

        A: for (int i=0; i<numbers.length; i++) {
            B: for (int j=0; j<numbers[i].length; j++) {

                System.out.print(i + ":" + j + " ");
                
                if (numbers[i][j] == 4) {
                    System.out.println("\nBreak from B");
                    break B;
                }

                if (numbers[i][j] == 8) {
                    System.out.println("\nBreak from A");
                    break A;
                }
            }    
        }
    }
}

/**
    0:0 0:1 0:2 1:0 
    Break from B
    
    2:0 2:1 
    Break from A
 */






Questions and answers:
Clink on Option to Answer




1. When you know how many times to loop

  • a) use for()
  • b) use while()

2. Enchanced loop

  • a) for (key in data) {}
  • b) for (String key:data) {}


References: