Tag Archives: empty statement

An Empty Statement—Nothing is something!

An empty statement in Java is written as a single semicolon. Execution of an empty statement always completes normally.

;

The empty statement doesn’t do anything, but the syntax is occasionally useful. For example, you can use it to indicate an empty loop body of a while loop, for example:

class NullStatement{
    public static void main(String []args){
        while(true);
    }
}

The above loop is a classic example of an infinite loop using the while statement. In the above case the condition would always be true. The empty statement would act as the body of the loop and on execution the while loop would keep on iterating in an infinite loop unless stopped by pressing Ctrl+C or Ctrl+Sift+R in case of BlueJ IDE.

Usually it’s assumed by students that empty statements can be used liberally anywhere in the program but that’s not true. Take a look at the following code snippet:

class NullStatement{
    public static void main(String []args){
        while(true);;
    }
}

The above code on casual inspection looks same as the earlier code using an empty statement which was executing infinite times. But the above code using two empty statements won’t even compile in Java. The compiler will detect that the while loop is infinite and the first empty statement is acting as the body of the loop. The second empty statement is actually something for the compiler and that something is never going to be executed because it’s being preceded by an infinite loop. Hence, a compile time error unreachable statement would occur.

Now inspect the following code:

class NullStatement{
    public static void main(String []args){
        while(false);;
    }
}

In this case it may appear to a casual reader the above code is perfectly normal because loop this time the second empty statement is reachable because the condition would always be false. Indeed the second empty statement is now reachable but now the first empty statement becomes unreachable because the condition is always going to be false!
Infact, the following code with only one empty statement will also not compile due to unreachable code because the condition would always be false:

class NullStatement{
    public static void main(String []args){
        while(false);
    }
}

In short for a compiler something is nothing and nothing is something! 🙂

Note: The above discussion is with respect to Java programming language.