When declaring a variable, you must also give it a name. A valid name is made up of characters from the set:
upper case letters
lower case letters
the underscore character
Actually, Java permits you to use other alphabetical characters, such as Ä and ç in variable names as well, but these characters may cause difficulty if you want to move your source code to other systems. It is best to stick to Roman letters without accents.
A variable name cannot begin with a digit, and the name must be unique. Neither you nor the compiler would be able to distinguish between variables with the same name. For some simple cases, using single letters such as i, j, k is enough, but as programs grow larger this becomes less informative. Like the name for a product or service, a variable name should do two things:
- be unique
- express the purpose
A good variable name is descriptive enough to indicate to a human reader how a variable is being used, for example countMessages,
userPreference, or customerName.
Complete the following table by renaming the bad variable names and providing descriptions.
Bad Variable Name
double current profit;
counts products sold this month
dollars earned this month