Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does code with successive semi-colons compile?

Tags:

java

According to my scientific Java experimentation, int x = 0; is equivalent to int x = 0;; which is equivalent to int x = 0;;;;;;;;;;;;;;;

  1. Why does Java allow for this? Does it have any practical application?
  2. Are each of these just empty statements? Do they actually take up any extra processing time during runtime? (I would assume they're just optimized out?)
  3. Do other languages do this? I'm guessing it's something inherited from C, like a lot of things in Java. Is this true?
like image 657
Tim Avatar asked May 08 '12 02:05

Tim


2 Answers

The extra semicolons are treated as empty statements. Empty statements do nothing, so that's why Java doesn't complain about it.

like image 70
Jordonias Avatar answered Oct 20 '22 05:10

Jordonias


As Jake King writes, you can produce empty statements to do nothing in a loop:

while (condition);

but to make it obvious, you would write

while (condition)
    ;

or even better:

while (condition)
/** intentionally empty */
    ;

or even better, as Michael Kjörling pointed out in the comment,

while (condition)
{
    /** intentionally empty */
}

More often, you see it in for-statements for endless loops:

for (;;)

or only one empty statement

for (start;;) 
for (;cond;) 
for (;;end) 

Another thing you can do, is, to write a program, once with one, and once with 2 semicolons:

public class Empty
{
    public static void main (String args[])
    {
        System.out.println ("Just semicolons");;
    }
}

Compile it, and run list the size of byte code (identic) and do an md5sum on the bytecode (identic).

So in cases, where the semantics aren't changed, it is clearly optimized away, at least for the 1.6-Oracle compiler I can say so.

like image 36
user unknown Avatar answered Oct 20 '22 03:10

user unknown