This "stupid question" is about the fact that "if (condition);" compiles, even though the erroneous semicolon makes it meaningless.
Why do stupid things compile?
This "stupid question" is about the fact that
if (condition); compiles, even though the erroneous semicolon makes it meaningless.
Editor's note: Sometimes the most interesting discussions begin when someone says, "This may be a stupid question, but ...." If the person asking the question has taken the time to think about the problem before asking, the question is often not stupid at all. The uncertainty points out an ambiguity in the specs, holes in the docs, or a search for how more experienced programmers might address a particular problem. From time to time, we will print one of the "(Not So) Stupid Questions" we receive and invite our readers to answer the question in the feedback section.
Remember that new people are joining the Java community all the time and may be looking for help from those with more experience. Also, those who began with Java as their first language can benefit from those coming to the community with experience in other languages. As always, answer the questions with kindness. You are also welcome to submit your questions to
This may be a stupid question, but ... "Why is
if (true); considered valid Java syntax?"
Quite often I track down a bug in my code to:
if ( condition );
When of course what I meant to type was:
if ( condition )
That is to say, without the first semicolon. If you accidentally put in the semicolon, the
consequence block gets executed regardless of the outcome of the
It would be great if the compiler would catch such things, but for some reason it compiles because it is considered valid syntax. So my question is, why would anybody want to do an
if condition that has no consequence? It feels a bit C-like to me. Would it be too late to tweak this corner case of the language spec (maybe with a
-source compiler flag) to stop this category of bugs?
I'm really looking forward to a response that tells me:
Why doesn't the compiler catch the pointlessness of
width="1" height="1" border="0" alt=" " />