1-Minute Quiz: Why is Hyphen Illegal in Identifier?

Why is hyphen (-) an illegal char in Java identifier? Why can't we use variable names like first-name, as we do in xml files? The answer to this question is not hard, but the challenge is, can you answer it in 1 minute. I didn't.
  • First, hyphen is the same symbol as the arithmetic operator minus. So for variables like first-name, we don't know if it's a single variable named first-name, or the numeric variable first minus another numeric variable name. Neither does the compiler. So the easiest solution is to disallow -. XML is a markup mark-up language, not programming language, so hyphen is no problem there.

  • Secondly, hyphen is already used in other operators like ->, though it's not in Java yet. If you have an expression like first-result->second, you don't know if it's a pointer operation, or a comparison between first-result- and second. Java has rejected -> from C++, but maybe one day it will take it from PHP.

Followers

Pageviews Last 7 Days