Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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;
like image 570
Malinda Avatar asked Jun 26 '17 13:06

Malinda


People also ask

Why can't variables start with numbers Java?

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.

Can a variable name start with number in Java?

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.

Why can't you start a variable name with a number?

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.

Can a Java name start with a number?

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.


2 Answers

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?

like image 158
Bathsheba Avatar answered Sep 21 '22 13:09

Bathsheba


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.
like image 21
GhostCat Avatar answered Sep 23 '22 13:09

GhostCat