Java: For each loop

This entry is part 11 of 54 in the series Learn Java

The for each loop gives an easy way to iterate through arrays.

On each iteration the next element in the array is assigned to the specified variable, and the loop continues to execute until it has gone through the entire array.

package javaapplication9;

public class JavaApplication9 {

    public static void main(String[] args) {

        int[] array = {1, 2, 3, 4, 5};
        
        for (int element : array) {
            System.out.print(element);
        }
        System.out.println();
    }
}

foreach

Java: For loop

This entry is part 9 of 54 in the series Learn Java

The for loop is used to go through a code block a specific number of times. It uses three parameters.

The first parameter initializes a counter and is always executed once, before the loop.

The second parameter holds the condition for the loop and is checked before each iteration.

The third parameter contains the increment of the counter and is executed at the end of each iteration.

package javaapplication8;

public class JavaApplication8 {

    public static void main(String[] args) {

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

for

 

 

Java: Conditional while loop

This entry is part 8 of 54 in the series Learn Java

The while loop runs through the code block only if the condition is true, and will continue looping for as long as the condition remains true.

The loop below will print out the numbers 0 to 9.

package javaapplication7;

public class JavaApplication7 {

    public static void main(String[] args) {
        int i = 0;
        while (i < 10) {
            System.out.print(i++);
        }
    }
}

In the example above, i is first set to 0.  As long as i is less than 10, it will print out i.

i is incremented using i++.

while

Java: If else statement

This entry is part 7 of 54 in the series Learn Java

The if else statement will check if a condition is true.

In the below example, we set a string a to be “Elton”.

Since (a == “Elton”) will evaluate to true, the first println statement will be executed.

package javaapplication6;

public class JavaApplication6 {

    public static void main(String[] args) {
       
        String a = "Elton";
        
        if (a == "Elton")
        {
            System.out.println("Crocodile Rock");
        } else
        {
            System.out.println("Uptown Girl");
        }
    }
}

if