Naming Variables
Data is stored for a program using variables. A variable is a named storage location.
Naming Variables
Unlike math class where you use a single letter as a variable name, in programming, we strive to have the code be as readable as possible by using longer, more descriptive variable names. Single letter variable names are acceptable, but not very readable and should be avoided in many cases. Variable names are case-sensitive, meaning lower case letters and upper case letters are treated as distinctly different characters and are not interchangeable. For example, myName and myname are completely different variable names.
Rules for Naming Variables
There are a few rules to follow when naming a variable:
- they can consist of letters, numbers, underscore (
_), and dollar sign ($).- By convention, the dollar sign (
$) is never used.
- By convention, the dollar sign (
- they cannot start with a number.
- By convention, they always start with a letter.
- they cannot be a Java keyword.
- A Java keyword is a word that is set aside with a specific meaning in the language. Our primitive data types, for example, are all considered Java keywords.
By convention, variables will start with a lower-case letter.
Some examples of variable names:
| Description | Acceptable Variable Names | Unacceptable Variable Names | Explanation of Example |
|---|---|---|---|
| Textbook price |
|
|
|
| Someone's first name |
|
|
|
| Whether an order is a combo meal or not |
|
|
|
| Vending Machine Price |
|
|
|
You will notice that since we cannot use blank space the underscore (_) symbol is used to space out the words for readability. Likewise, you can use a mix of lowercase and uppercase letters to break up the words, starting each subsequent word with an uppercase letter. Such as comboMeal. This is called camel-case.