Previous Section  < Day Day Up >  Next Section

Assigning Variable Types

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:

  • 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 // Coming soon: variables. Delete the comment 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 for the moment this variable is an empty storage space. 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 non-decimal numbers you will need in your computer programs. It can hold any integer ranging 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.

By the Way

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 written recommendation from my parole officer.


Characters and Strings

Because 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 also can 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 = "Larvets";


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:


String productName = Larvets;


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.

By the Way

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 website 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.

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 = "Larvets";

7:    }

8: }


To compile the program using the JDK 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, as you'll discover later in this hour.

By the Way

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."


Other Numeric Variable Types

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:


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 numeric variable types, long, is typically used for integers that are too big for the int type to hold. A long integer can be almost any size: If the number has five commas or fewer 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 called boolean that only can 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:

  • 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 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 turtle-squashing Italian plumbers), 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.

By the Way

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.


    Previous Section  < Day Day Up >  Next Section