Rules For Defining Java Identifiers
There are certain rules for defining a valid Java identifier. These rules must be followed, otherwise, we get a compile-time error. These rules are also valid for other languages like C, and C++.
- The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid Java identifier as it contains a ‘@’ a special character.
- Identifiers should not start with digits([0-9]). For example “123geeks” is not a valid Java identifier.
- Java identifiers are case-sensitive.
- There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letters only.
- Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement as a while is a reserved word. There are 53 reserved words in Java.
Examples of valid identifiers :
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers :
My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
Java Identifiers
In Java, identifiers are used for identification purposes. Java Identifiers can be a class name, method name, variable name, or label.
Example of Java Identifiers
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
In the above Java code, we have 5 identifiers namely :
- Test: class name.
- main: method name.
- String: predefined class name.
- args: variable name.
- a: variable name.
Contact Us