14

Why are special characters (except $, _) not allowed in Java variable names?

pap
  • 27,064
  • 6
  • 41
  • 46
NPKR
  • 5,368
  • 4
  • 31
  • 48

3 Answers3

20

This is not the case - many special characters are actually valid for identifiers. It is defined in the JLS #3.8:

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.
[...]
A "Java letter" is a character for which the method Character.isJavaIdentifierStart(int) returns true.
A "Java letter-or-digit" is a character for which the method Character.isJavaIdentifierPart(int) returns true.

For example, this is a valid variable name:

String sçèêûá¢é£¥ = "bc";

You can see all the valid characters with this simple code:

public static void main(String args[]) {
    for (int i = 0; i < Character.MAX_VALUE; i++) {
        if (Character.isJavaIdentifierPart(i)) {
            System.out.println("i = " + i + ": " + (char) i);
        }
    }
}

ps: nice examples on @PeterLawrey's blog

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 2
    I think your example would be clearer if the variable name started with "special" character such as: String çèêûá¢é£¥ = "bc"; – cquezel Dec 11 '13 at 15:21
16

There is actually an enormous number special characters which are allowed in Java identifiers as it is. For example, you can have every currency symbol, and all 10 continuation characters(not just _)

if( ⁀ ‿ ⁀ == ⁀ ⁔ ⁀ || ¢ + ¢== ₡)

Even more bizarrely you can have characters which are invisible or cause the text to be printed backwards.

The following program has \u202e in its identifiers resulting in it "special" appearance.

for (char c‮h = 0; c‮h < Character.MAX_VALUE; c‮h++)
    if (Character.isJavaIdentifierPart(c‮h) && !Character.isJavaIdentifierStart(c‮h))
        System.out.printf("%04x <%s>%n", (int) c‮h, "" + c‮h);

This prints all the special characters allowed in an identifier which compiles and runs.

http://vanillajava.blogspot.co.uk/2012/09/hidden-code.html

http://vanillajava.blogspot.co.uk/2012/08/uses-for-special-characters-in-java-code.html

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
8

The following code is all valid in Java...

int Δ = 1;
double π = 3.141592;
String 你好 = "hello";
Δ++;
System.out.println(Δ);

I'd say those are pretty special characters for variable names.

Source : http://rosettacode.org/wiki/Unicode_variable_names#Java

David
  • 19,577
  • 28
  • 108
  • 128