Rules for defining Java Identifiers


Before we go through the Rules for defining Java Identifiers, if you are not aware with what is Java Identifiers you can check out here Java Identifiers

There are certain rules for defining a valid java identifiers. These rules must be followed, otherwise we get compile-time error. These rules are also valid for other languages like C,C++.

1. Only allowed characters for identifiers are all alphanumeric ([a to z],[A to Z],[0 to 9]) and '$' dollar sign and '_' underscore sign.

2. Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java identifier.

3. Java identifiers are case-sensitive. (Example - number, Number, NUMBER)

4. There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letters only.

5. Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement as while is a reserved word. There are 53 reserved words in Java.

Valid Java Identifiers:
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123

Invalid Java 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


Question: Which of the following are valid Java Identifiers?

  1. total_number
  2. total#
  3. 123total
  4. Total123
  5. Ca$h
  6. _$_$_$_$_
  7. all@hands
  8. Java2share
  9. Integer
  10. Int
  11. int

Answer: Valid Java Identifiers are 1, 4, 5, 6, 8, 9, 10

Happy Learning !

Comments

Popular posts from this blog

Explain public static void main in Java

Reserve or Key Words in Java

OOPs concepts in Java with Examples