user4751087
user4751087

Reputation:

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 some documentation about it, but unfortunately I could not find any explanation why is a legal code declaration. Only references to 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]);
    }

}

Upvotes: 3

Views: 215

Answers (4)

Stephen C
Stephen C

Reputation: 719259

Please note that in the documentation only mention the following syntax:

The syntax of enhanced for loop is:

for(declaration : expression)
{
   //Statements
}

The "documentation" quoted your question comes from a page on TutorialsPoint (as seen by me on 2016-05-22). I'm not going to link to it, but assuming they have not corrected it (yet), you should be able to find it using a Google phrase search.

This is NOT the official documentation. The only official documentation for Java is the documentation written by Oracle (and previously Sun Microsystems) employees and published by these organizations.

TutorialsPoint has no standing. In this case, they have simply gotten the Java syntax wrong.

According to the Java 8 JLS, the real Java syntax for the enhanced for loop is1

EnhancedForStatement:
    for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) 
         Statement

EnhancedForStatementNoShortIf:
    for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) 
         StatementNoShortIf

where Statement and StatementNoShortIf include the empty statement; i.e. a bare semi-colon.


1 - The grammar rules are quoted from the Java 8 grammar. The "no short ifs" variant is about disambiguating nested if statements, and is not relevant here. In the Java 7 JLS, there are two versions of the grammar in the spec, one with the variants and one without them.

Upvotes: 2

user5549921
user5549921

Reputation:

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".

Specifically, WHY it doesn't fail, is the way the for-loop syntax is laid out. This was explained very well in Stephen C's answer:

According to the Java 8 JLS, the real Java syntax for the enhanced for loop is

EnhancedForStatement:
    for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) 
         Statement

EnhancedForStatementNoShortIf:
    for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) 
         StatementNoShortIf

As you can see, Statement refers to any valid statement, which includes the usage of ;, as ; is a valid "Statement". Because this is allowed, there is no reason why it should fail in any case.

Infact, another way to interpret for (int i = 0; i < 5; i++); would be:

"For every time i is less than 5, run statements, 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);

Upvotes: -1

Roland Illig
Roland Illig

Reputation: 41676

The documentation that you read is not the official documentation, since the authors would have written:

The enhanced for statement has the form for (declaration : expression) statement

This is because the braces are not needed.

A single semicolon forms a so-called _ empty statement_, and that makes your code snippet syntactically valid.

Upvotes: 1

James
James

Reputation: 8586

https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html

A for loop is defined as:

  for ( ForControl ) Statement

; is a valid statement in Java, as is a block of statements. Not something you see often with this form of loop, but you can do things like:

 int i = 2;
 for(; i < 100; i*=2);
 // i is now the smallest power of two greater than 100

Upvotes: 2

Related Questions