B.Demille B.Demille - 6 months ago 10
Java Question

Why enhanced for loop does not fail when ends with semicolon?

I'm studying for a Java certification and on one of the mock exams I saw a very odd implementation of For loop. The exercise showed the following syntax :

for (Days d: Days.values());


At the beginning, I thought that it was a syntax error, since I always knew that the syntax for the "For loop" requires curly braces or, if there is only one instruction to iterate we can skip the curly braces and set our statement aligned just after the loop.
-- Since I haven't seen before a For loop ending with semicolon ";".--

Then I tried to find something on the documentation of Java 7, but unfortunately I could not find any explanation why is a legal code declaration. Please note that in the documentation only mention the following syntax:

The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements
}


The odd thing is that after all of this, I tested my code and surprisingly it compiled and ran properly. Then, based on some tests that I did (playing with the code), I discovered that it seems that the ";" works like a For loop empty but with curly braces, so, any instruction after it, it is executed only one time. (As if the code where out of the loop). But I'm not sure if this is the right interpretation of the semicolon on the enhanced for loops.

Please see the complete example:

package com.TestDays;
public class TestDays {
public enum Days { MON, TUE, WED};
public static void main(String[] args) {
int x = 0;
*for (Days d: Days.values());*
Days[] d2 = Days.values();
System.out.println(d2[2]);
}

}



  • Does anyone knows why this syntax is allowed?
    Thank you.


Answer

There are 3 main different ways a for-loop or enhanced for-loop can be created in Java:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

for (int i = 0; i < 5; i++) System.out.println(i);

for (int i = 0; i < 5; i++);

These 3 loops are equivalent to:

  1. For every time i is less than 5, do whatever is between {} and increment its value by one.
  2. For every time i is less than 5, print i and increment its value by one.
  3. For every time i is less than 5, increment its value by one.

Its not a matter of, "why doesn't it fail", its more, "what the for-loop is being told to do". Leaving a ; at the end is a good way to leave the loop ready for future code; as a placeholder.

Another thing to point out, placing a ; on a random line in Java code, does not throw an error either. The ; is a valid statement in Java. Another way to interpret for (int i = 0; i < 5; i++); would be:

"For every time i is less than 5, run all indented statements or those on the same line, and increment its value by one."

Same rules can be applied to:

for (Integer i : ints) {
    System.out.println(i);
}

for (Integer i : ints) System.out.println(i);

for (Integer i : ints);
Comments