Which of the following are legal identifiers.
-
2variable
-
variable2
-
_whatavariable
-
3
- $anothervar
-
#myvar
Java identifiers must start with a letter, underscore (), or dollar sign ($), and can contain digits thereafter. 'variable2', '_whatavariable', '_3', and '$anothervar' are all valid. '2variable' starts with a digit and '#myvar' starts with #, making them invalid.
To answer this question, we need to understand the rules for legal identifiers in programming.
In most programming languages, including Java, the following rules generally apply for legal identifiers:
- They can only contain letters (a-z, A-Z), digits (0-9), underscores (_), and dollar signs ($).
- They must start with a letter, an underscore, or a dollar sign.
- They cannot be a reserved keyword or a special symbol.
Let's go through each option to determine whether it is a legal identifier or not:
Option A) 2variable - This option is not a legal identifier because it starts with a digit, which violates rule 2.
Option B) variable2 - This option is a legal identifier because it starts with a letter, satisfies rule 1, and does not violate rule 3.
Option C) _whatavariable - This option is a legal identifier because it starts with an underscore, satisfies rule 1, and does not violate rule 3.
Option D) 3 - This option is a legal identifier because it starts with an underscore, satisfies rule 1, and does not violate rule 3.
Option E) $anothervar - This option is a legal identifier because it starts with a dollar sign, satisfies rule 1, and does not violate rule 3.
Option F) #myvar - This option is not a legal identifier because it contains a hash symbol (#), which is not allowed according to rule 1.
Therefore, the correct options are B, C, D, and E. These options are legal identifiers according to the given rules.