An identifier can be viewed as a sequence of valid characters such as letters, numbers, dollar-sign, and underscore characters that are used to name classes, variables, and methods for uniquely identifying them.
Further, Java is case-sensitive, meaning, “TEST” and “test” are not considered as same. An identifier must not start with a number as the resultant identifier would be treated as an invalid.
Below are the examples of valid identifiers in Java :
test, Test, te1st, $test, te_st
Below are the invalid identifiers in Java :
2test, te-st, te/st
A legal identifier always starts with a letter or dollar sign or underscore, and its succeeding characters can be the letter, digits, dollar, and underscore.
public class MyClass { public static void main(String[] args) { int test = 0; } }
A Java compiler follows certain rules to validate a valid identifier, if it is considered invalid, then a compiler would throw a compile-time exception.
Therefore, one needs to follow certain rules to define a valid identifier.
An identifier should have meaningful names as it increases code readability. In Java, there are certain naming conventions that one should follow while naming a class, variable, or method. However, these are not required to follow strictly but are considered as a good coding habit.
These are the following conventions :
1) An identifier should be in camel-case if the name is constructed by combining two or more words. For example, “userName”, “getSum()”
2) A method or variable name should begin with a lowercase letter. for example, “result”,”getSum()”.
3) A class or interface name should start with a capital letter. for example, “User”, “String”
4) A variable defined as a constant should be in capital letters and if it is made from two or more words then “_” should be used in between. For example, “PI”, “USER_NAME”
A reserved keyword depicts a predefined meaning and functionality to the compiler which acts as one of the basic building blocks to write a program.
A reserved keyword cannot be used as a variable name or identifier. There are 50 Keywords in JAVA and 3 literals. Using any of these in a program as an identifier would trigger a compile-time error.
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 |
This post was last modified on August 20, 2022