ptg7068951
54 HOUR 5:Storing and Changing Information in a Program
Naming Your Variables
Variablenames in Java can begin with a letter, underscore character (_), or
a dollar sign ($). The rest of the name can be any letters or numbers. You
can give your variables any names you like but should be consistent in
how you name variables. This section outlines the generally recommended
naming method for variables.
Java is case-sensitive when it comes to variable names, so you must always
capitalize variable names the same way. For example, if the gameOvervari-
able is referred to as GameOversomewhere in the program, an error pre-
vents the program from being compiled.
A variable’s name should describe its purpose in some way. The first letter
should be lowercase, and if the variable name has more than one word,
make the first letter of each subsequent word a capital letter. For instance,
if you want to create an integer variable to store the all-time high score in a
game program, you can use the following statement:
int allTimeHighScore;
You can’t use punctuation marks or spaces in a variable name, so neither
of the following works:
int all-TimeHigh Score;
int all Time High Score;
If you try these variable names in a program, NetBeans responds by flag-
ging the error with the red alert icon alongside the line in the source editor.
Storing Information in Variables
You can store a value in a variable at the same time that you create the
variable in a Java program. You also can put a value in the variable at any
time later in the program.
To set a starting value for a variable upon its creation, use the equal sign
(=). Here’s an example of creating a double floating-point variable called pi
with the starting value of 3.14:
doublepi = 3.14;
All variables that store numbers can be set up in a similar fashion. If you’re
setting up a character or a string variable, quotation marks must be placed
around the value as described earlier in this hour.