Manas Tripathi
Manas Tripathi

Reputation: 27

There is no semicolon after while in do while loop, even then the code is not throwing syntax error or compile time error why

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int i = 0;
        do while ( i < 10 )
        System.out.print("The value of i is " + i);
        while ( i > 10 ) ;
    }
}

Why is this code not throwing syntax error? There is no semicolon after while.

Upvotes: 1

Views: 233

Answers (2)

Sterconium
Sterconium

Reputation: 579

Because your code is not written as you think:

It is a do while, that "does" the inner while.

After the do the compiler looks for the code block immediately after, usually enclosed in { }. If there is not a { (therefore no block) the code evaluates the next line alone as a block. In this case the while is "the block".

Then it looks for the "block" of this while, and again, there is no { after so it evaluates the next line as its block.

The print line ends with ; so the code is legal and this block is ok.

Suggestion: always enclose code blocks between { and }, even when not mandatory to avoid useless confusion. It is actually legal to do it even if there is no loop (it can be exploited for variable visibility purposes, but nobody does it nor know about it)

Hope I helped

PS: there is no increment of i, so the code will run endlessly.

Upvotes: 1

Anonymous
Anonymous

Reputation: 86323

Your code is perceived in this way:

    int i = 0;
    do {
        while (i < 10) {
            System.out.print("The value of i is " + i);
        }
    } while (i > 10);

The do is coupled with the second while, not the first one. It’s customary to have a block statement ({}) between do and while, but Java allows any statement there, including a while statement.

(As an aside your inner loop is an infinite loop, so your snippet doesn’t terminate. But this was not what you were asking.)

Upvotes: 5

Related Questions