2.2. Identifiers

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?

  1. byte exam_total = 7;
  2. int exam-Total = 1090;

The correct answer is (a). Option (b) is incorrect because hyphens aren’t allowed in the name of a Java identifier. Underscores are allowed.

2.2.1. Valid and invalid identifiers

Table 2.7 contains a list of rules that will enable you to correctly define valid (and invalid) identifiers, along with some examples.

Table 2.7. Ingredients of valid and invalid identifiers

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.

Table 2.8. Java keywords and reserved words that can’t be used as names for Java variables
abstract default goto package this
assert do if private throw
boolean double implements protected throws
break else import public transient
byte enum instanceof return true
case extends int short try
catch false interface static void
char final long strictfp volatile
class finally native super while
const float new switch  
continue for null synchronized  

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.181