REMEMBER JAVA

MINTE9
2REMEMBER




Last update:   23-07-2021

For loop

p114 You can use normal for-loop when you know how many times you want to loop.
 RunCode
/**
 * Normal For-Loop
 */
class App {
            
    public static void main(String[] args) {
        
        for (int i=0; i<10; i++) {
            System.out.println(i); // 0 1 2 .. 9
        }

        // The three expressions of the for loop are optional
        int k=0; for ( ;; ) { // infinite loop
            System.out.println(k++); // 0 1 2 .. 20
            
            if (k > 20) break;
        }
    }
}
... 15 lines
˄˄˄
Enhanced for-loop allows each element visit without tracking the index.
 RunCode
/**
 * Enhanced For-Loop (improved)
 */

class App {
            
    public static void main(String[] args) {
        
        int[] numbers = {1, 2, 3, 4, 5};

        for (int no : numbers) {
            System.out.println(no); // 1 2 .. 5
        }
    }
}
... 11 lines
˄˄˄
With Java 8 we can use forEach to loop a Map, List, Set or Stream.
 RunCode
import java.util.Arrays;
import java.util.List;

/**
 * Java 8 forEach
 */

class App {
            
    public static void main(String[] args) {
        
        List<Integer> numbers = Arrays.asList(1, 2, 3);

        // lambda
        numbers.forEach(x -> System.out.println(x)); // 1, 2, 3

        // method reference
        numbers.forEach(System.out::println); // 1, 2, 3
    }
}
... 14 lines
˄˄˄
While    (2/3)

While

A while loop has only the boolean test. Usefull to keep going until some condition is true.
 RunCode
class LearningApp {
            
    public static void main(String[] args) {
        
        int i = 0;

        while(i<10) {

            System.out.println(i); // 0 1 2 ... 9

            i++;
        }
    }
}
... 9 lines
˄˄˄

Break

The break statement can be labeled or unlabeled.
 RunCode
class LearningApp {
            
    public static void main(String[] args) {
        
        int[][] numbers = { {1,2,8}, {4,5,6}, {7,8,9} };

        first: // Look Here
        for (int i=0; i<numbers.length; i++) {

            second:
            for (int j=0; j<numbers[i].length; j++) {
                
                if (numbers[i][j] == 8) {

                    System.out.println("Found 8 at " + i + ":" + j);

                    break first; // Found 8 at 0:2 / break labeled

                    //break; // Found 8 at 2:1 / break unlabeled
                }
            }    
        }
    }
}
... 16 lines
˄˄˄
Task

 CompleteTask
class LearningApp {
            
    public static void main(String[] args) {
        
        String[] names = {"John", "Marry", "Ana"};

        /**
         * Make a for-each loop and ...
         * Output all names
         */

        ...
    }
}
solution code
Questions    
No. 6   Numbers
CARD
05
63

        A B C D E F
🔔
1/2