Reputation: 4365
According to my scientific Java experimentation, int x = 0;
is equivalent to int x = 0;;
which is equivalent to int x = 0;;;;;;;;;;;;;;;
Upvotes: 9
Views: 1703
Reputation: 143906
One thing to note is that if you do something like this:
public int foo()
{
return(0);;
}
The compiler will/may complain about an unreachable statement because there's an empty statement after a return. At least with Oracle's 1.6 sdk it does.
Upvotes: 0
Reputation: 36250
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.
Upvotes: 18
Reputation: 43872
Yes, they are empty statements, which don't do anything at all. They are optimized out by the compiler, but in some cases this empty statement actually does something, doing the same thing as a set of empty braces ({}
). They are inherited from C syntax, but they have few uses in Java. In C, sometimes doing something like this was useful:
while (condition);
This will loop until condition
is false, preventing code from progressing. However, this is discouraged in modern code, and shouldn't ever really be used in Java. However, the empty statement does count as a statement, just a useless one, so constructs like this:
if (condition);
doSomething();
....may cause somewhat baffling results. The if
statement will call the empty statement, not the method, so the method will always be called. Just a caveat to keep in mind.
Upvotes: 7
Reputation: 5848
The extra semicolons are treated as empty statements. Empty statements do nothing, so that's why Java doesn't complain about it.
Upvotes: 21