7

Java allows identifier to start with or contain $ (dollar sign). e.g int a$b;

But why # is not allowed in an identifier? What is the specific reason? Is # an operator or something in Java? e.g int a#b;

Ajinkya Kulkarni
  • 984
  • 2
  • 11
  • 19

3 Answers3

8

I'd say that it is a combination of readability and the historical antecedents of the language. Remember that the Java syntax was designed to be easy-on-the-eye for C and C++ programmers. (And as @dan04 points out, the # character is significant in most dialects of C and C++.)

Incidentally, while $ is technical legal in Java identifiers, it is reserved for use by compilers, code generators and other things. If you use $ in identifiers in your source code, you risk getting into trouble with collisions with synthetic identifiers produced by (for example) the javac compiler.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

I doubt there was a specific reason for disallowing # as much as there was a general aversion to punctuation in identifiers (which could look like operators). Special exceptions were made in order to deal with WORD_SEPARATION and Inner$Classes.

In C and C++, on which Java's syntax is based, # is used for preprocessor directives.

dan04
  • 87,747
  • 23
  • 163
  • 198
1

Variables can contain letters, digits, underscores and dollar signs - excluding #, @, ~ ,`

I guess this is for the sake of readability - int s#@t; seems odd.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140