14

In Java, variable names start with a letter, currency character ($) etc. but not with number, :, or .

Simple question: why is that?

Why doesn't the compiler allow to have variable declarations such as

int 7dfs;
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Malinda
  • 524
  • 2
  • 5
  • 11
  • The downvote is probably a reflection of the poorly worded title, and the format of the question body. Do consider addressing those. – Bathsheba Jun 26 '17 at 13:45
  • @Malinda You have asked a number of questions, if there are solutions which solve your problems, do consider accepting them. – user3437460 Jun 26 '17 at 14:13
  • Because the language rules forbid it! See the JLS. – Lew Bloch Jun 26 '17 at 14:15
  • This syntax detail of Java has been taken over from C++ and C (and possibly BCPL, I don’t know). It has also spread into many other langauges (not only C#). Since a lot of people know more than one language, a lot of people would be confused if the rules were changed. You *may* change the rules if you’ve got strong reasons; apparently they didn’t have here. – Ole V.V. Jun 26 '17 at 14:25

2 Answers2

44

Simply put, it would break facets of the language grammar.

For example, would 7f be a variable name, or a floating point literal with a value of 7?

You can conjure others too: if . was allowed then that would clash with the member selection operator: would foo.bar be an identifier in its own right, or would it be the bar field of an object instance foo?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
22

Because the Java Language specification says so:

IdentifierChars:

JavaLetter {JavaLetterOrDigit}

So - yes, an identifier must start with a letter; it can't start with a digit.

The main reasons behind that:

  • it is simply what most people expect
  • it makes parsing source code (much) easier when you restrict the "layout" of identifiers; for example it reduces the possible ambiguities between literals and variable names.
Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248