Java: For loop


for (counter; predicate; change counter) {
  // loop body

// eg
for (var index = 10; index >= 0; index--) {
  // ...

The for loop statement is essentially a shorthand notation for while, which allows you to declare a counter, specify its initial value, and the termination condition is more compact - usually in one line of code. Here's how the implementation of the reversal of the line will change if instead of while using for:

static String reverseString(String str) {
    var result = "";

    for (var index = str.length() - 1; index >= 0; index--) {
        var currChar = str.charAt(index);
        result = result + currChar;

    return result;

You can read like this: “the loop with the index repeats as long as index >= 0 and after each step decreases the index by 1”.

And due to the fact that this whole phrase is collected in one line of code and is also readable in it (if the initial value, the predicate and the change can be written briefly), clarity of the code benefits from this.

In the definition of the for loop there is:

  1. the initial value of the counter
  2. predicate-condition for repeating cycles
  3. description of how the counter changes after each step

The principle of operation is exactly the same as that of the while loop. Traditionally, the for loop is used with counters, when a certain counter takes values from M to N with a certain step. Of course, no one bothers to use it, for example, in this form:

var s = "";
for (; s.length < 3; ) { s += "*"; }
  • this code creates the string s from three "asterisks", with neither the declaration of the counter, nor the instruction for changing the counter is indicated - only the condition being checked. But in such cases - when there is no counter - the for loop has no advantage in compactness of the code over the while and then the while is usually used.

Let's take a look at the program flow using the example of a function call with a simple string:


There are 3 characters in the string, so the loop will have 3 iterations.


Implement the function sumOfSeries, which counts the sum of a series of integers. The series is given by two numbers - the initial and final.

The function takes two argument-numbers and returns the sum of the series. For example, for arguments 4, 7 the sum would be 4 + 5 + 6 + 7 = 22.

sumOfSeries(1, 2); // => 3
sumOfSeries(1, 3); // => 6
sumOfSeries(4, 7); // => 22

If the initial and final numbers are equal, then the result will be the same number:

sumOfSeries(1, 1); // => 1

If you got stuck and don't know what to do, you can ask a question in our huge and friendly community