Malinda
Malinda

Reputation: 584

Why can't Java variable names start with a number?

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;

Upvotes: 15

Views: 12952

Answers (2)

GhostCat
GhostCat

Reputation: 140417

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.

Upvotes: 22

Bathsheba
Bathsheba

Reputation: 234635

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?

Upvotes: 44

Related Questions