Variables and Assignment Statements
Read this chapter, which covers variables and arithmetic operations and order precedence in Java.
6. Names for Variables
Answer:
Yes — as long as the names answer
and rate
have not already been used.
Variables
The programmer picks a name for each variable in a program. Various things in a program are given names. A name chosen by a programmer is called an identifier. Here are the rules for identifiers:
- Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', and characters '$' and '_'.
- An identifier can not contain the space character.
- Do not start with a digit.
- An identifier can be any length.
- Upper and lower case count as different characters.
SUM
andSum
are different identifiers.
- An identifier can not be a reserved word.
- An identifier must not already be in use in this part of the program.
A reserved word is a word which has a predefined meaning in Java. For example int
, double
, true
, and import
are reserved words. Rather than worry about the complete list of reserved words, just remember to avoid using names that you know already mean something, and be prepared to make a change if you accidentally use a reserved word you didn't know.
Although dollar sign is legal in identifiers, by convention it is used for special purposes. Don't use it for ordinary variables, even if the compiler lets you.
Although legal, it is unwise to start an identifier with underscore. Also, older Java compilers allowed a single underscore as an identifier, but recent ones do not.
As a matter of programming style, a name for a variable usually starts with a lower case letter. If a name for a variable is made of several words, capitalize each word except the first. For example, payAmount
and grandTotal
. These conventions are not required by syntax, but make programs easier to read.
Question 6:
Which of the following variable declarations are correct? (click on a declaration to verify your answer)