Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not allowed to use the character š„ž in a Java source code file as a variable name?

What are the rules for the characters that can be used in Java variable names?

I have this sample code:

public class Main {
    public static void main(String[] args)  {
        int kš„ž = 4;
        System.out.println(s);
    }
}

which will not compile:

javac Main.java
Main.java:3: error: illegal character: '\udd1e'
        int kš„ž = 4;
              ^
1 error

So why is the Java compiler throwing an error for 'š„ž' ? (\uD834\uDD1E)

Same in ideone.com: http://ideone.com/fnmvpG

like image 234
Koray Tugay Avatar asked Jan 28 '16 19:01

Koray Tugay


People also ask

Which Cannot be used for a variable for Java?

Blank spaces cannot be used in variable names. Java keywords cannot be used as variable names. Variable names are case-sensitive.

What characters are allowed in a variable name Java?

A variable's name can be any legal identifier ā€” an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ".

Can we use identifier as variable name in Java?

You cannot use keywords like int , for , class , etc as variable name (or identifiers) as they are part of the Java programming language syntax. Here's the complete list of all keywords in Java programming.

Can variables be capital letters in Java?

For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.


1 Answers

What are the rules for the characters that can be used in Java variable names?

The rules are in the JLS for identifiers, in section 3.8. You're interested in Character.isJavaIdentifierPart:

A character may be part of a Java identifier if any of the following are true:

  • it is a letter
  • it is a currency symbol (such as '$')
  • it is a connecting punctuation character (such as '_')
  • it is a digit
  • it is a numeric letter (such as a Roman numeral character)
  • it is a combining mark
  • it is a non-spacing mark
  • isIdentifierIgnorable(codePoint) returns true for the character

Of course, that assumes you're compiling your code with the appropriate encoding.

The character you're apparently trying to use is U+1D11E, which is none of the above. It's a musical treble clef, which is in the "Symbols, other" category.

like image 91
Jon Skeet Avatar answered Oct 13 '22 21:10

Jon Skeet