DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
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:
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.
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 } }
Go ahead and save these lines before making any changes.
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.
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.
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."
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.
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:
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.
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.
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:
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 again 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 that 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 upon 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 weight 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.
1: class Elvis { 2: public static void main(String[] arguments) { 3: int weight = 250; 4: System.out.println("Elvis weighs " + weight); 5: System.out.println("Elvis visits a few all-you-can-eat rib joints."); 6: System.out.println("Elvis throws a Thanksgiving luau."); 7: weight = weight + 10; 8: System.out.println("Elvis now weighs " + weight); 9: System.out.println("Elvis discovers aerobics."); 10: weight = weight - 15; 11: System.out.println("Elvis now weighs " + weight); 12: System.out.println("Elvis falls into a washing machine during the 13: shrink cycle."); 14: weight = weight / 3; 15: System.out.println("Elvis now weighs " + weight); 16: System.out.println("Elvis accidentally clones himself 12 times."); 17: weight = weight + (weight * 12); 18: System.out.println("The 13 Elvii now weigh " + weight); 19: } 20: }
When you're done, save the file and use the javac tool to compile the program.
In the same directory as the Elvis.java file, type the following command
to compile the Elvis program:
javac Elvis.java
If it compiles without any errors, you will not see any output; javac responds only if something goes wrong. If you do see error messages, check the line number that is listed in the error message to look for typos. Correct any typos that you find and compile the program.
Next, run the program by typing the following command:
java Elvis
Listing 5.3 shows the output for this program.
Elvis weighs 250 Elvis visits a few all-you-can-eat rib joints. Elvis throws a Thanksgiving luau. Elvis now weighs 260 Elvis discovers aerobics. Elvis now weighs 245 Elvis falls into a washing machine during the shrink cycle. Elvis now weighs 81 Elvis accidentally clones himself 12 times. The 13 Elvii now weigh 1053
As in the other programs that you have created, the Elvis program uses a
main() block statement for all of its work. This statement can be divided
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 it is used throughout the program to monitor Elvis' weight.
The next line is similar to several other statements in the program:
System.out.println("Elvis weighs " + weight);
The System.out.println() command displays a string that is contained within the parentheses. In the preceding line, the text Elvis weighs is displayed, followed by the value of the weight variable. There are numerous System.out.println() statements in the program. If you're still unclear about how these statements work, look at each of them in Listing 5.2 and compare them to the corresponding lines in Listing 5.3.
Four different mathematical expressions are used in the Elvis program to add weight to Elvis, subtract weight from Elvis, divide it, and finish it off with some multiplication. Each of these expressions uses symbols (+, -, *, /, and %) called operators. You will be using these operators to crunch numbers throughout your Java programs.
An addition expression in Java uses the + sign, as in Line 7 of your program:
weight = weight + 10;
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.
A subtraction expression uses the - sign, as in Line 10:
weight = weight - 15;
This expression sets the weight variable equal to its current value minus 15. The weight variable is now equal to 245.
A division expression uses the / sign, as in Line 13:
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 that you can use to find the remainder of a division. When the value of the weight variable was divided by 3 in Line 13, a remainder of 2 was discarded in order for weight to remain as an integer value. To find a remainder from an expression, use the % operator. You could use the following statement to find the remainder of 245 divided by 3:
remainder = 245 % 3;
A multiplication expression uses the * sign. Line 16 uses a multiplication expression as part of a more complicated statement:
weight = weight + (weight * 12);
The weight * 12 part of the expression multiplies weight by 12. The full statement takes the current value of weight and adds it to weight multiplied by 12. This example shows how more than one expression can be combined in a statement. The result is that weight becomes 1,053--in other words, 81 + (81 * 12).
One thing you will need to do often is to change the value of a variable by 1. Because this task is so common, there are special, simplified ways to accomplish it in your Java programs. You can increase the value by 1, which is called incrementing the variable, or decrease the value by 1, which is decrementing the variable. You use special operators for each of these tasks.
To increment the value of a variable by 1, use the ++ operator, as in the following statement:
x++;
This statement adds 1 to the value stored in the x variable.
To decrement the value of a variable by 1, use the -- operator:
y--;
This statement reduces y by 1.
During Hour 1, "Becoming a Programmer," the name of the C++ programming language was described as a joke you'd understand later on. 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 instead of just one. If you're still having trouble, C++ adds new features and functionality to the C programming language in the same way that the ++ operator adds 1 to a variable. Just think: After you work through all 24 hours of this book, you'll be able to tell jokes that are incomprehensible to more than 99 percent of the world's population.
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 statement:
x = y * 3 + 5;
Unless you know what order the computer will use when working out the math in this expression, you cannot be sure what the x variable will be set to. If y is equal to 10 and multiplication occurs before addition, x will equal 35. If y equals 10 and addition occurs before multiplication, x will equal 80.
The following order is used when working out an expression:
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 statement:
int number = 5++ * 6 + 4 * 10 / 2;
This statement sets the number variable to 56. How does the computer come up with this number? First, the increment operator is handled, and 5++ is set to the value of 5 increased by 1--in other words, 6. The expression then becomes the following:
int number = 6 * 6 + 4 * 10 / 2;
Now, multiplication and division are handled from left to right. First, 6 is multiplied by 6. Then 4 is multiplied by 10 and that result is divided by 2 (4 * 10 / 2). The expression becomes the following:
int number = 36 + 20;
This expression results in the number variable being set to 56.
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 a statement.
Now that you have been introduced to variables and expressions, you can give a wide range of instructions to your computer in a program. Programs that you write can accomplish many of the same tasks as a calculator by handling sophisticated mathematical equations with ease. Manipulating numbers is only one element of variable use. You also can handle 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.
Test your knowledge of variables, expressions, and the rest of the information in this hour by answering the following questions.
You can review the topics of this hour more fully with the following activities: