Identifiers are names of packages, classes, interfaces, methods, and variables. Though identifying a valid identifier is not explicitly included in the exam objectives, there’s a good chance that you’ll encounter a question similar to the following that will require you to identify valid and invalid identifiers:
Question: Which of the following lines of code will compile successfully?
The correct answer is (a). Option (b) is incorrect because hyphens aren’t allowed in the name of a Java identifier. Underscores are allowed.
Table 2.7 contains a list of rules that will enable you to correctly define valid (and invalid) identifiers, along with some examples.
Properties of valid identifiers |
Properties of invalid identifiers |
---|---|
Unlimited length | Same spelling as a Java reserved word or keyword (see table 2.8) |
Starts with a letter (a–z, upper- or lowercase), a currency sign, or an underscore | Uses special characters: !, @, #, %, ^, &, *, (, ), ', :, ;, [, /, , } |
Can use a digit (not at the starting position) | Starts with a Java digit (0–9) |
Can use an underscore (at any position) | |
Can use a currency sign (at any position): ¤, $, £, ¢, ¥, and others | |
Examples of valid identifiers | Examples of invalid identifiers |
customerValueObject | 7world (identifier can’t start with a digit) |
$rate, £Value, _sine | %value (identifier can’t use special char %) |
happy2Help, nullValue | Digital!, books@manning (identifier can’t use special char ! or @) |
Constant | null, true, false, goto (identifier can’t have the same name as a Java keyword or reserved word) |
You can’t define a variable with the same name as Java keywords or reserved words. As these names suggest, they’re reserved for specific purposes. Table 2.8 lists Java keywords, reserved words, and literals that you can’t use as identifier names.
Let’s combat some of the common mistakes when determining correct and incorrect variables using the following variable declarations:
Next, let’s look at the object reference variables and how they differ from the primitive variables.
3.147.85.181