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 an integer number in a variable called debt. Integers are only one of the types of information that can be stored in variables. Variables also can hold characters, lines of text, floating-point numbers, and other things.
Variables are the main way that a computer remembers something as it runs a program. The BigDebt program used the debt variable to tell the computer that the national debt increases by $59 million per day. The computer needed to remember that fact a little later so a minute's worth of debt increase could be calculated. During this hour, you'll learn more about using variables in your Java programs.
The following topics will be covered during this hour:
· Creating variables
· The different types of variables
· Storing values into variables
· Using variables in mathematical expressions
· Putting one variable's value into another variable
· Increasing and decreasing a variable's value
Statements and Expressions
Computer programs are a set of instructions that tell the computer what to do. Each of these instructions is called a statement. The following example from a Java program is a statement:
int HighScore = 400000;
In a Java program, you can use brackets to group statements. These groupings are called block statements. Consider the following portion of a program:
1: public static void main (String[] arguments) {
2: int a = 3;
3: int b = 4;
4: int c = 8 * 5;
5: }
Lines 2-4 of this example are a block statement. The opening bracket on Line 1 denotes the beginning of the block, and the closing bracket on Line 5 denotes the end of the block.
Some statements are called expressions because they involve a mathematical expression. Line 4 in the preceding example is an expression because it sets the value of the c variable equal to 8 multiplied by 5. You'll be working with several different types of expressions throughout the coming sections.
Assigning Variable Types
In a Java program, variables are created with a statement that must include two things:
· The name of the variable
· The type of information the variable will store
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
}
}
Go ahead and save these lines before making any changes.
Integers and Floating-Point Numbers
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. This statement 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 that 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.
A floating-point variable could be used to store a grade point average such as 2.25, to pick a number that's dear to my heart. It also could 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.
Characters and Strings
Because all the variables you have dealt with so far are numeric, you might have the mistaken impression that all variables are used with numbers. 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;:
char key = `C';
String productName = "Orbitz";
When you are using character values in your program, such as in the preceding example, you must put single quote marks on both sides of the character value being assigned to a variable. You must surround string values with double quote marks. These quote 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:
String productName = Orbitz;
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 Orbitz. However, because there are no quote marks around the word Orbitz, the computer is being told to set the productName value to the same value as a variable named Orbitz.
After adding the char and String statements, your program should 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 the javac compiler tool to make sure it was created correctly.
Listing 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 = "Orbitz";
7: }
8: }
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 that you create in a Java program. For more information, see the section called "Storing Information in Variables."
Although the other variable types are all lowercase letters (int, float, char), the capital letter is required in the word String when creating String variables. A string in a Java program is somewhat different than the other types of information you will use in variables. You'll learn about this distinction in Hour 6, "Using Strings to Communicate."
Other Numeric Variable Types
The variables that you have been introduced to so far will be the main ones that 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:
byte escapeKey = 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:
short roomNumber = 222;
The last of the special numeric variable types, long, is typically used for integers that are too big for the int type to hold. A long integer can be of almost any size; if the number has five commas or less when you write it down, it can fit into a long. Some six-comma numbers can fit as well.
Except for times when your integer number is bigger than 2.14 billion or smaller than -2.14 billion, you won't need to use any of these special variable types very often. If they're muddling your understanding of variable types, concentrate on int and float. Those types are the ones you'll be using most often.
The boolean Variable Type
Java has a special type of variable that can only be used to store the value true or the value false. This type of variable is called a boolean. 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:
· Has the user pressed a key?
· Is the game over?
· Is this the first time the user has done something?
· Is the bank account overdrawn?
· Have all 10 images been displayed onscreen?
· Can the rabbit eat Trix?
The following statement is used to create a boolean variable called gameOver:
boolean gameOver = false;
This variable has the starting value of false, and a statement such as this one could 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 of 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 quote 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 British mathematician who was mostly self-taught until late adulthood, invented Boolean algebra, a fundamental part of computer programming, digital electronics, and logic.
Naming Your Variables
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 that 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.
Caution: 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 GameOver statement will cause an error when you compile the program.
First, the name that you give a variable 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 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 could use the following statement:
int allTimeHighScore;
You can't use punctuation marks or spaces in a variable name, so neither of the following would work:
int all-TimeHigh Score;
int all Time High Score;
If you tried to use these names in a program, the Java compiler would respond with an error.
Storing Information in Variables
As you have seen, in a Java program you can put a value into a variable at the same time that you create the variable. You also can 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 equals sign (=). The following is an example of creating a floating-point variable called pi with the starting value of 3.14:
float pi = 3.14;
All variables that store numbers can be set up in a similar fashion. If you're setting up a variable for a character or a string, you must place quote marks around the value as shown previously.
You also can set one variable equal to the value of another variable if they both are of the same type. Consider the following example:
int mileage = 300;
int totalMileage = mileage;
First, an integer variable called mileage is created with a starting value of 300. In the second line, an integer variable called totalMileage is created with the same value as mileage. Both variables will have the starting value of 300. In future hours, you will learn ways to convert one variable's value to the type of another variable.
Caution: 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:
WarGame.java:7: Variable warships may not have been initialized.
warships = warships + 10;
^
1 error
إرسال تعليق