Hour 5. Storing and Changing Information in A Program
Hour 5. Storing and Changing Information in A Program
Hour 5. Storing and Changing Information in A Program
In Hour 2, "Writing Your First Program," you used a variable, a special storage place that is used to
hold information. The information stored in variables can be changed as your program runs, which is
why they're called variables.
Your first program stored a string of text in a variable called greeting. Strings are only one type of
information that can be stored in variables. They can also hold characters, integers, floating-point
numbers, and other things.
During this hour, you'll learn more about using variables in your Java programs, including the
following topics:
• Creating variables
Variables are the main way that a computer remembers something as it runs a program. The Saluton
program in Hour 2 used the greeting variable to hold "Saluton mondo!", a message in Esperanto. The
computer needed to remember that text a little later, so that the message could be displayed.
In a Java program, variables are created with a statement that must include two things:
To see the different types of variables and how they are created, load the word processor you're using
to write programs and set it up to start a new file. You will be creating a program called Variable.
Give your new file the name Variable.java and start writing the program by entering the following
lines:
class Variable {
public static void main(String[] arguments) {
// Coming soon: variables
}
}
So far, the Variable program has a main() block with only one statement in it—the comment line //
Coming soon: variables. Delete the comment line and enter the following statement in its place:
int tops;
This statement creates a variable named tops. It does not specify a value for tops,so the variable is an
empty storage space for the moment. The int text at the beginning of the statement designates tops as
a variable that will be used to store integer numbers. You can use the int type to store most of the
nondecimal numbers you will need in your computer programs. It can hold any integer from –2.14
billion to 2.14 billion.
Create a blank line after the int tops; statement and add the following statement:
float gradePointAverage;
This statement creates a variable with the name gradePointAverage. The float text stands for floating-
point numbers. Floating-point variables are used to store numbers that might contain a decimal point.
Note
A floating-point variable can be used to store a grade point average, such as 2.25, to pick a number
that's dear to my heart. It also can be used to store a number such as 0, which is the percentage chance
of getting into a good graduate school with that grade point average, despite my really good cover
letter and a compelling written recommendation from my parole officer.
Because all the variables you have dealt with so far are numeric, you might have the impression that
all variables are used as a storage place for numbers. Think again. You can also use variables to store
text. Two types of text can be stored as variables: characters and strings. A character is a single letter,
number, punctuation mark, or other symbol. Most of the things you can use as characters are shown
on your computer's keyboard. A string is a group of characters.
Your next step in creating the Variable program is to create a char variable and a String variable. Add
these two statements after the line float gradePointAverage;:
When you are using character values in your program, such as in the previous example, you must put
single quotation marks on both sides of the character value being assigned to a variable. You must
surround string values with double quotation marks. These quotation marks are needed to prevent the
character or string from being confused with a variable name or other part of a statement. Take a look
at the following statement:
This statement might look like a statement that tells the computer to create a string variable called
productName and give it the text value of Larvets. However, because there are no quotation marks
around the word Larvets, the computer is being told to set the productName value to the same value as
a variable named Larvets.
If you're wondering about Larvets, the product mentioned in this section, it's a snack made from
edible worms that have been killed, dried, and mixed with the same kinds of nuclear flavoring as
Doritos chips. You can order Larvets in three flavors—BBQ, cheddar cheese, and Mexican spice—
from the mail-order retailer HotLix at the Web site http://www.hotlix.com/larvets.htm or by calling 1-
800-EAT-WORM.
After adding the char and String statements, your program will resemble Listing 5.1. Make any
changes that are needed and be sure to save the file. This program does not produce anything to
display, but you should compile it with your Java compiler to make sure it was created correctly.
Example 5.1. The Variable Program
1: class Variable {
2: public static void main(String[] arguments) {
3: int tops;
4: float gradePointAverage;
5: char key = 'C';
6: String productName = "Larvets";
7: }
8: }
To compile the program using the SDK compiler, type the following command:
javac Variable.java
The last two variables in the Variable program use the = sign to assign a starting value when the
variables are created. You can use this option for any variables you create in a Java program. For
more information, see the section called "Storing Information in Variables" later in this hour.
Note
Although the other variable types are all lowercase letters (int, float, and char), the capital letter is
required in the word String when creating string variables. A string in a Java program is somewhat
different from the other types of information you will use in variables. You'll learn about this
distinction in Hour 6, "Using Strings to Communicate."
The variables you have been introduced to so far will be the main ones you use during this book and
probably for most of your Java programming. There are a few other types of variables you can use in
special circumstances.
You can use three other variable types with integers. The first, byte, can be used for integer numbers
that range from –128 to 127. The following statement creates a variable called escapeKey with an
initial value of 27:
The second, short, can be used for integers that are smaller in size than the int type. A short integer
can range from –32,768 to 32,767, as in the following example:
There are two numeric types for decimal numbers: float, which can handle numbers with around 38
digits to the right or left of the decimal point, and double, which supports even more digits—as many
as 324.
Java has a special type of variable called boolean that can only be used to store the value true or the
value false. At first glance, a boolean variable might not seem particularly useful unless you plan to
write a lot of computerized true-or-false quizzes. However, boolean variables will be used in a variety
of situations in your programs. The following are some examples of questions that boolean variables
can be used to answer:
This variable has the starting value of false, and a statement such as this one can be used in a game
program to indicate that the game isn't over yet. Later on, when something happens to end the game
(such as the destruction of all the player's acrobatic Italian laborers), the gameOver variable can be set
to true. Although the two possible boolean values—true and false—look like strings in a program,
you should not surround them with quotation marks. Hour 7, "Using Conditional Tests to Make
Decisions," describes boolean variables more fully.
Boolean numbers are named for George Boole, who lived from 1815 to 1864. Boole, a mathematician
who was mostly self-taught until late adulthood, invented Boolean algebra, a fundamental part of
computer programming, digital electronics, and logic. One imagines that he did pretty well on true-
false tests as a child.
Variable names in Java can begin with a letter, underscore character (_), or a dollar sign ($). The rest
of the name can be any letters or numbers, but you cannot use blank spaces. You can give your
variables any names you like under those rules, but you should be consistent in how you name
variables. This section outlines the generally recommended naming method for variables.
Note
Java is case-sensitive when it comes to variable names, so you must always capitalize variable names
in the same way throughout a program. For example, if the gameOver variable is used as GameOver
somewhere in the program, the use of GameOver will cause an error when you compile the program.
For starters, the name you give a variable will 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 wanted 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 will work:
If you tried to use these names in a program, the Java compiler would respond with an error.
You can put a value into a variable at the same time that you create the variable in a Java program.
You can also put a value in the variable at any time later in the program.
To set up a starting value for a variable upon its creation, use the equal sign (=). The following is an
example of creating a floating-point variable called pi with the starting value of 3.14:
double pi = 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 shown previously.
You can also set one variable equal to the value of another variable if they both are of the same type.
Consider the following example:
Note
If you do not give a variable a starting value, you must give it a value before you try to use it. If you
don't, when you attempt to compile your program, the javac compiler will respond with an error
message such as the following:
Another naming convention in Java is to capitalize the names of variables that will not change in
value. These variables are called constants. The following creates three constants:
int TOUCHDOWN = 7;
int FIELDGOAL = 3;
int PAT = 1;
Because constants never change in value, you might wonder why one should ever be used—you can
just use the value assigned to the constant instead. One of the advantages of using constants is that
they can make a program easier to understand. For example, the variables Font.BOLD and
Font.ITALIC are constants that hold integer values representing the style of the current font.
As you worked on a particularly unpleasant math problem in school, did you ever complain to a
higher power, protesting that you would never use this knowledge in your life? Sorry to break this to
you, but all your teachers were right—those math skills are going to be used in your computer
programming.
That's the bad news. The good news is that the computer will do any of the math you ask it to do. As
mentioned earlier in this hour, any instructions you give a computer program involving math are
called expressions. Expressions will be used frequently in your computer programs. You can use them
for tasks such as the following:
As you write computer programs, you will find yourself drawing on your old math lessons as you use
expressions. Expressions can use addition, subtraction, multiplication, division, and modulus division.
To see expressions in action, return to your word processor and close the Variable.java file if it is still
open. Create a new file and save it as Elvis.java. The Elvis program creates a fictional person whose
weight loss and gain can be tracked with mathematical expressions. Instead of adding statements to
the program piece-by-piece, enter the full text of Listing 5.2 into the word processor. Each part of the
program will be discussed in turn.
When you're done, save the file and compile the program. If you're using the SDK, in the same folder
as the Elvis.java file, type the following at a command line to compile the Elvis application:
javac Elvis.java
If it compiles without any errors, you will not see any output; javac only responds if something goes
wrong. If you do see error messages, check the line number that is listed in each error message to look
for typos. Correct any typos you find and compile the program.
Next, run the program. SDK users should type the following at a command line:
java Elvis
As in the other programs you have created, the Elvis program uses a main() block statement for all its
work. This statement can be broken into the following five sections:
Line 3 creates the weight variable and designates it as an integer variable with int. The variable is
given the initial value 250 and used throughout the program to monitor Elvis' weight.
Four different mathematical expressions are used in the Elvis program—to add weight to Elvis,
subtract weight from Elvis, divide Elvis, and finish off with some multiplied Elvii. Each of these
expressions uses symbols (+, -, *, /, and %) called operators. You will be using these operators to
crunch numbers throughout your Java programs.
This line sets the weight variable equal to its current value plus 10. Because the weight was set to 250
when it was created, Line 7 changes weight to 260.
This expression sets the weight variable equal to its current value minus 15. The weight variable is
now equal to 245.
weight = weight / 3;
The weight variable is set to its current value divided by 3 and rounded down because weight is an
integer. The weight variable is now equal to 81.
There's another expression you can use to find the remainder of a division. When the value of the
weight variable was divided by 3 in Line 14, a remainder of 2 was discarded in order for weight to
remain as an integer value. To find a remainder from a division expression, use the % operator. You
can use the following statement to find the remainder of 245 divided by 3:
A multiplication expression uses the * sign. Line 17 uses a multiplication expression as part of a more
complicated statement:
A common task in programs is to change the value of a variable by one. You can increase the value by
one, which is called incrementing the variable, or decrease the value by one, which is decrementing
the variable. There are operators to accomplish each of these tasks.
To increment the value of a variable by one, use the ++ operator, as in the following statement:
x++;
y--;
You also can put the increment and decrement operators in front of the variable name, as in the
following statements:
++x;
--y;
Putting the operator in front of the variable name is called prefixing, and putting it after the name is
called postfixing. You probably have many cherished memories of grade school language lessons,
when you learned about prefixes such as "pre-", "extra-", and "de-". A prefixed operator is like a
prefix in a word—it comes first. Postfixed operators lag behind. (If your memories of those classes
are not-so-cherished, you must not have sat behind Mary Beth Farkas.)
Although it might seem redundant for Java to include both prefixed and postfixed operators, the
difference becomes important when you use the increment and decrement operators inside an
expression.
int x = 3;
int answer = x++ * 10;
What does the answer variable equal after these statements are handled? You might expect it to equal
40—which would be true if 3 was incremented by 1, which equals 4, and then 4 was multiplied by 10.
However, answer is set to 30. The reason is that the postfixed operator was used instead of the
prefixed operator.
When a postfixed operator is used on a variable inside an expression, the variable's value won't
change until after the expression has been completely evaluated. The statement int answer = x++ * 10
does the same thing, in the same order, as the following two statements:
The opposite is true of prefixed operators. If they are used on a variable inside an expression, the
variable's value changes before the expression is evaluated.
int x = 3;
int answer = ++x * 10;
This does result in the answer variable being equal to 40. The prefixed operator causes the value of
the x variable to be changed before the expression is evaluated. The statement int answer = ++x * 10
does the same thing, in order, as these statements:
x++;
int answer = x * 10;
At this point, you might be ready to say, "Prefixing, postfixing, incrementing, decrementing—let's
call the whole thing off!" It's easy to become exasperated with the ++ and — operators, because
they're not as straightforward as many of the concepts you'll encounter in this book.
There's some good news: You don't need to use the increment and decrement operators in your own
programs. You can achieve the same results by using the + and – operators. Incrementing and
decrementing are useful shortcuts, but taking the longer route in an expression is fine, too.
During Hour 1, "Becoming a Programmer," the name of the C++ programming language was
described as a joke you'd understand later. Now that you've been introduced to the increment operator
++, you have all the information you need to figure out why C++ has two plus signs in its name
instead of just one. Prepare to laugh: Because C++ adds new features and functionality to the C
programming language, it can be considered an incremental increase to C. Hence the name C++. After
you work through all 24 hours of this book, you also will be able to tell jokes that are
incomprehensible to more than 99 percent of the world's population.
Operator Precedence
When you are using an expression with more than one operator, you need to know what order the
computer will use as it works out the expression. Consider the following statements:
int y = 10;
x = y * 3 + 5;
Unless you know what order the computer will use when working out the math in the last statement,
you cannot be sure what the x variable will be set to. It could be set to either 35 or 80, depending on
whether y * 3 is evaluated first or 3 + 5 is evaluated first.
Because multiplication takes place before addition, you can revisit the previous example and come up
with the answer:
int y = 10;
x = y * 3 + 5;
In the last statement, y is multiplied by 3 first, which equals 30, and then 5 is added. The x variable is
set to 35.
Comparisons will be discussed during Hour 7. The rest has been described during this hour, so you
should be able to figure out the result of the following statements:
int x = 5;
int number = x++ * 6 + 4 * 10 / 2;
How does the computer come up with this total? First the increment operator is handled, and x++ sets
the value of the x variable to 6. However, make note of the fact that the ++ operator is postfixed after
x in the expression. This means that the expression is evaluated with the original value of x.
Because the original value of x is used before the variable is incremented, the expression becomes the
following:
int number = 5 * 6 + 4 * 10 / 2;
Now, multiplication and division are handled from left to right. First, 5 is multiplied by 6, 4 is
multiplied by 10, and that result is divided by 2 (4 * 10 / 2). The expression becomes the following:
If you want an expression to be evaluated in a different order, you can use parentheses to group parts
of an expression that should be handled first. For example, the expression x = 5 * 3 + 2; would
normally cause x to equal 17 because multiplication is handled before addition. However, look at a
modified form of that expression:
x = 5 * (3 + 2);
In this case, the expression within the parentheses is handled first, so the result equals 25. You can use
parentheses as often as needed in an expression.
Summary
Now that you have been introduced to variables and expressions, you can give a wide range of
instructions to your computer in a program. With the skills you have developed during this hour, you
can write programs that accomplish many of the same tasks as a calculator, handling sophisticated
mathematical equations with ease.
Numbers are only one kind of thing that can be stored in a variable. You also can store characters,
strings of characters, and special true or false values called boolean variables. The next hour will
expand your knowledge of String variables and how they are used.