What is an identifier in Java?
Java Identifiers are nothing but the name of class, interface, method, or variable. For example
int message = “Welcome”
Where int is the data type and message is the identifier/ variable name.
Let’s take a look at the simple program and identify its identifiers.
Class Welcome { public static void main (String args[]) { int message ="Welcome to JavaInterviewPoint" } }
In the above code, we have 5 identifiers
- Welcome – Class name
- main – Method name
- String – Class name
- args – Variable name
- message – Variable name
Rules for Java Identifiers
Below are the rules which needs to be followed while defining an identifier
- Identifiers can only have characters (a-z, A-Z, 0-9), dollar sign ($), and underscore (_) characters.
Example: String Java –> Valid Identifier
int total# –> Invalid Identifier as # is not allowed in Identifier.
- Identifiers cannot start with a number or any other character, other than character (a-z, A-Z), dollar sign ($), or underscore (_) character.
Example: String msg –> Valid Identifier
int $cash –> Valid Identifier
int _total –> Valid Identifier
int 123total –> Invalid Identifier, as an identifier cannot start with a number
int #total –> Invalid Identifier, # cannot be used as the starting character
- There is no length limitation for Java Identifiers
Example: String mmmmmmeeeeeeeeessssssssssaaaaaaaagggggeeeeeeeeeee, is still a valid identifier, but it is not recommended to use a longer identifier as it will spoil the readability of the code.
- Java Identifiers are case sensitive
Example: String message = “Welcome”
String Message =” To”
String MESSAGE = “JavaInterviewPoint”
All the above identifiers are different
- Java reserved keywords cannot be used as an Identifier. The below list should never be used as an identifier
abstract |
continue |
for |
new |
switch |
assert |
default |
goto |
package |
synchronized |
boolean |
do |
if |
private |
this |
break |
double |
implements |
protected |
throw |
byte |
else |
import |
public |
throws |
case |
enum |
instanceof |
return |
transient |
catch |
extends |
int |
short |
try |
char |
final |
interface |
static |
void |
class |
finally |
long |
strictfp |
volatile |
const |
float |
native |
super |
while |
- All the predefined classes and interface names can be used as an identifier.
Example: int String
int Exception
String Runnable
The above identifiers are still a valid identifier but not recommended.
Below are some of the valid identifiers
String WelcomeMessage;
int $rate;
int total_number;
String _flag;
int $;
String _$_$;
Invalid Identifiers
int 99Value;
String #total;
int @123;
int 5G;
Leave a Reply