Java Identifiers
Java identifiers
- In programming languages, identifiers are used for identification purpose. In Java an identifier can be a class name, method name, variable name or a label.
- Identifiers are the name given to variables, classes, methods etc. Consider the Below code;
int score;
Here, score is a variable (an identifier). You cannot use keywords as variable name. Its because keywords have predefined meaning. For example,
int float;
The above code is wrong. Its because float is a keyword and cannot be used as a variable name.
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.
Rules for Naming an Identifier
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, C++.
- An identifier cannot be a keyword.
- Identifiers are case-sensitive.
- It can have a sequence of letters and digits. However, it must begin with a letter, $ or _. The first letter of an identifier cannot be a digit.
- Its convention to start an identifier with a letter rather and $ or _.
- Whitespaces are not allowed.
- Similarly, you cannot use symbols such as @, #, and so on.
Here are some valid identifiers:
score
level
highestScore
number1
convertToString
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
easyto123
Here are some invalid identifiers:
class
float
1number
highest Score
@pple
My Variable // contains a space
123easyto // 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
Series:
Java Tutorials Hub
