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;
Use of a digit to begin a variable name makes error checking during compilation or interpertation a lot more complicated. Allowing use of variable names that began like a number would probably cause huge problems for the language designers.
Rules to Declare a Variable A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and two special characters such as _ underscore and $ dollar sign. The first character must not be a digit.
We can not specify the identifier which starts with a number because there are seven phases of compiler as follows. None of above supports that a variable starts with a number. This is because the compiler gets confused if is a number or identifier until it reaches an alphabet after the numbers.
The rules for Java variable naming are fairly lax. The first letter of a variable must be either a letter, dollar sign or an underscore. After that, any combination of valid Unicode characters or digits is allowed.
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
?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With