5/28/2006

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.

6 comments:

Anonymous said...

Because it's a reserved token and Java doesn't require whitespace in unary and binary operations?

Anonymous said...

"-> ...though it's not in Java yet."

Let's hope it never gets into Java syntax...

Anonymous said...
This comment has been removed by a blog administrator.
amar said...

some times you can, not exactly compare but check for hyphen in string.
eg; Pattern.compile("[a-zA-Z0-9,\\._`\' -]*");

but location of hyphen might matter. like placing it at last works.

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Iqbal Dlk said...

very nice and informative blog
dot net training in chennai
java training in chennai