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
Blank spaces cannot be used in variable names. Java keywords cannot be used as variable names. Variable names are case-sensitive.
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 " _ ".
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.
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.
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:
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.
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