Once Mark Zuckerberg noted that computers are really good in a repetition of commands. It is not simple for a human being, we are getting tired of repetitions the same thing many times in a row, but a computer can do it millions and billions of times and never get bored. If you try to send greetings to all Facebook users, there is no human to have days enough to do it. However you can make a computer to solve this task by writing a few lines of code. This is how loops work. They let us not to repeat the same routine actions. For loop in Java - 1The most popular loop in Java is the so-called defined loop or for loop.

How to write a for loop in Java? For loop in general

For loop executes some statements for a certain number of times. For example, writing fifty times “I must not be so, ho-ho, ho” or sending invitations to all your friends are typical tasks for this kind of loop. The syntax of the most common version of for loop:
for ([counter initialization]; [checking conditions]; [changing of the counter])
{
    //  statements
}
The initialization expression is executed once, then the condition is evaluated, which should be a boolean expression.
  • When the loop begins the initializations executes.
  • When the conditions evaluate to false, our loop stops its work.
The counter is changing, usually incrementation (or decrementation) happens after each iteration through the loop. You can skip any of the three loop expressions (initialization, checking condition, changing of the counter). The loop condition is checked before the next step of the loop. If the condition is false, the program goes out of the loop and continue with the instruction following the for construct. Here we have a block diagram of for loop. For loop in Java - 2

How to use for loop in Java. Simple example.

Here is a particular Java for loop example. Let’s write ten times "Hello!" String each time it would be from the new line with a number of this line. We should get the next output:
  1. Hello!
  2. Hello!
  3. Hello!
  4. Hello!
  5. Hello!
  6. Hello!
  7. Hello!
  8. Hello!
  9. Hello!
  10. Hello!
Here is our Java program that solves this problem:
public class ForExample {
   public static void main(String[] args) {
       for (int i = 0; i < 10; i++) {
           System.out.println(i + 1 + ". Hello!");
       }
   }
}

How it works?

Step 1. Counter i = 0. Loop checks our condition, i << 10, hence, loop statements are executed. It prints the phrase "1. Hello!". 1 is a string i + 1 (because we counted from zero, but the first line is still the first). Counter i is incremented. Now, i = 1. Step 2. Counter i = 1. i < 10, so we’ve got a phrase "2. Hello!" and i + 1 = 2. … Step 10. Counter i = 9, we’ve got "10. Hello!" and i is incremented to 10. Step 11. Counter i = 10. i < 10 ? No, it is false. Therefore, the loop is ended. For loop in Java - 3

While loop and for loop: differences and similarities

In Java indefinite loop or while loop is continuously executed if the boolean condition comes true. The syntax of while loop:
while (boolean condition)
       {
            loop statements...
       }
Pretty often you may choose which one loop you want to use. Sometimes they are very close and you can use both of them. For example, here is the code for the same task (writing ten times "Hello!" with a number of the line) wrote with while loop:
public class ForAndForEach {
   public static void main(String[] args) {
       int j = 0;  //  we use the counter this way
       while (j < 10) {
           System.out.println(j + 1 + ". Hello!");
           j++;
       }
   }
}
However, professional programmers do not really like the while loop, and wherever possible, try to use the for loop.
FOR WHILE

We use the for loop if we already knew the number of iterations.

We use while loop if we don’t know exactly the number of iterations.

Initialization, condition checking and counter changing is already stitched in the syntax of a loop

Initialization and condition checking inside the loop. You may additionally use counter in statements.

Infinite loop for:

for(;;){
	System.out.println("working...");
}

Infinite loop while:

while(true){
	System.out.println("working...");
}

How to exit a for loop in java

Usually a for loop is running like a flow and the natural way to exit a loop is when a condition takes a false value. However there are two control statements that allow you to exit the loop before you’ll get the false value of a condition — break and continue.
  • break lets to exit current loop body as if the loop condition has evaluated to false.
  • continue makes the loop to jump to the next step (iterating the counter) without executing the statements.
Let’s solve the next problem using break and continue. We have an array of names and we say hello to everyone from this array except the strangers. So if we meet a “Stranger” string during our loop we exit it (go away and stop to say hello to anyone else).
public class ForBreakExample {
   public static void main(String[] args) {
       String[] names = {"Mike", "Dustin", "Stranger", "Lucas", "Will"};
       for (int i = 0; i < names.length; i++) {
//  how to break out of a for loop, java: check if we have any "Stranger" in  //  our array
if (names[i].equals("Stranger")) {
               System.out.println("I don't chat with strangers");
               break;
           }
           System.out.println("Hello," + names[i]);
       }
   }
}
The result of our program execution is:
Hello,Mike
Hello,Dustin
I don't chat with strangers
See? We ran away from the loop before we greeted Lucas and Will. Now let’s use continue, just to ignore a "Stranger" but stay inside the loop to say hello to other friends.
public class ForContinueExample {
   public static void main(String[] args) {
       String[] names = {"Mike", "Dustin", "Stranger", "Lucas", "Will"};
       for (int i = 0; i < names.length; i++) {
           if (names[i].equals("Stranger")) {
               System.out.println("I don't chat with strangers");
               continue;
           }
           System.out.println("Hello," + names[i]);
       }
   }
}
The result is:
Hello,Mike
Hello,Dustin
I don't chat with strangers
Hello,Lucas
Hello,Will
Excellent! We greeted all the friends, but didn’t talk to a stranger.

Enhanced version of for loop or for-each

For-each is a kind of for loop that is used when you need to process all elements of an array or collection. Actually, the very phrase for-each is not used in this cycle. The syntax is as follows:
for (type itVar: array)
{
    Block of operators;
}
Where type is the type of the iterative variable (the same as the data type of the array), ItVar is its name, array is the array or there can be another data structure, for example, ArrayList. As you can see, there is no counter, the iteration variable iterates over the elements of an array or collection, and not the index values. When such a loop is executed, the iteration variable is sequentially assigned the value of each element of the array or collection, after which the specified block of statements (or operator) is executed. Attention: the for-each loop can be applied to arrays and any classes that implement the java.lang.Iterable interface. Let’s solve the same problem with greetings friends, ignoring strangers ("Stranger") but this time use for-each loop.
public class ForEachExample {
   public static void main(String[] args) {
       String[] names = {"Mike", "Dustin", "Stranger", "Lucas", "Will"};
	//  for each loop, Java code
       for (String name : names) {
           if (name.equals("Stranger")) {
               System.out.println("I don't chat with strangers");
               continue;
           }
           System.out.println("hello, " + name);
       }
   }
}