Identifiers
What is identifier.
- A Name in Java program is called identifier, which can be used for identification purpose.
- It can be a class name, interface name, method name, label name, variable name etc.
Example
- In the above example words marked with red underline are identifiers.
- As you can see there are 5 identifiers
- Test (Class Name)
- main (Method Name)
- String (Pre-defined Class Name)
- args (Variable Name)
- println(Method Name)
Rules / Convention for Identifier Naming
While defining Java identifier name, we have to follow some rules as listed below.
- Allowed characters in Java identifier are listed below.
- A to Z (Uppercase letters)
- a to z (Lowercase letters)
- 0 to 9 (Digits)
- _ (Underscore)
- $ (Dollar sign)
- Example:
- contact_number (✓)
- contact# (✕)
- Identifier can't starts with digit.
- Example
- abc123 (✓)
- 123abc (✕)
- Java is a case sensitive language all variable listed below are different, but it is not a good programming practice.
- int total = 10; (✓)
- int TOTAL = 10; (✓)
- int Total = 10; (✓)
- In Java, there is not limit on the length of identifier name, but it is a good programming practice to keep your variable short, readable and meaningful.
- Keywords / Reserved words are not allowed as identifiers.
- Example
- int a = 10; (✓)
- int if = 10; (✕)
- You can use predefined class names and interface names as identifier name, but it is not recommended to use predefined names, it creates conflicts and confusion.
- Example
- int String = 111; (✓)
- int Runnable = 555; (✓)
Example of Valid / Invalid Java Identifiers
- father_name (✓)
- my_number (✓)
- my# (✕)
- 123abc (✕)
- abc123 (✓)
- ca$h (✓)
- _$_$_$ (✓)
- contact@me (✕)
- it2utor (✓)
- w3schools (✓)
- Integer (✓)
- int (✕)
- Int (✓)
- my-address (✕)
Comments