Identifiers
A "name" in Java is by default considered an identifier, which can be used for identification purpose. An identifier can be a class name, method name, variable name or label name. A name which can be used for identification is called an identifier.
In the example above, the identifiers highlighted are Test (class name), main (method name), String (class name; "String" is a predefined Java class name), args (variable name) and x (variable name).
While choosing a name, we should follow certain rules and conventions. Identifiers that follow rules and conventions are considered valid identifiers. Rules and conventions for defining Java identifiers:
- Rule: Characters: a-zA-Z0-9$_ (The only allowed characters in Java identifiers are alphanumeric characters, $ (dollar symbol) and _ (underscore). If any other characters are used, there will be a compile time error.
- Rule: Identifier cannot not start with a numeric character.
- Rule: Java identifiers are case-sensitive (we can differentiate Java identifiers using case).
import java.lang.*; class Test { public static void main(String[] args) { int number = 10; int Number = 20; int NUMBER = 30; } }In the example above, all three variable names are considered unique and different by Java. Java is a case-sensitive programming language.
- Rule: There is no length limit for Java identifiers.
- Convention: Although there is no length limit for Java identifiers, it is not good programming practice to use very lengthy identifiers, as it makes programs hard to read.
- Rule: Reserved keywords cannot be used as identifiers.
- Convention: All predefined Java class names and interface names can be used as identifiers e.g. String, Runnable, however it is not good programming practice to use them as identifiers because it can cause confusion and reduce code readability.
import java.lang.*; class Test { public static void main(String[] args) { int String = 888; System.out.println(String); int Runnable = 999; System.out.println(Runnable); } }In the example above, String is a predefined Java class name and Runnable is a predefined Java interface. They can be used as identifiers and the program will compile and run, although it is a valid Java program, it is against convention to do this.
| identifier | valid |
|---|---|
| total_number | yes |
| total# | no |
| total123 | yes |
| 123total | no |
| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz | yes |
| x | yes |
| if | no |
| _$_$_$_ | yes |
| int | no |
