Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Teach Yourself Java 1.1 Programming in 24 Hours

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> Teach Yourself Java 1.1 Programming in 24 Hours


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 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:

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:

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:

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


Workshop: Using Expressions

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.

Listing 5.2. The Elvis program.


 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.

Listing 5.3. The output of the Elvis 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:

1. Lines 3-4: The initial weight of Elvis is set to 250.

2.
Lines 5-8: Elvis gains weight.

3.
Lines 9-11: Elvis loses weight.

4.
Lines 12-14: Elvis reduces in size dramatically.

5.
Lines 15-17: Elvis multiplies.

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.

All About Operators

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

Incrementing and Decrementing a Variable

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.

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

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

Q&A

Q Is a line in a Java program the same thing as a statement?

A
No. Although the programs that you will create in this book put one statement on each line, this is done to make the programs easier to understand; it's not required. The Java compiler does not consider lines, spacing, or other formatting issues when compiling a program. The compiler just wants to see semicolons at the end of each statement. You can put more than one statement on a line, although this is not generally recommended.

Q Is there a reason to set up a variable without giving it a value right away?

A
For many of the simple programs that you will be creating in the first several hours, no. However, there are many circumstances where it makes more sense to give a variable a value at some point later in the program. One example would be a calculator program. The variable that stores the result of a calculation will not be needed until a user tries out the program's calculator buttons. Therefore, you would not need to set up an initial value when creating a result variable.

Q What's the specific range for the long variable type?

A
In Java, a long integer variable can be anything from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. This range ought to give your mathematical expressions plenty of breathing room when you can't use int, which has a range of -2,147,483,648 to 2,147,483,647.

Q Why should the first letter of a variable name be lowercase, as in gameOver?

A
It makes the variable easier to spot among all of the other elements of a Java program. Also, by following a consistent style in the naming of variables, you eliminate errors that can occur when you use a variable in several different places in a program. The style of naming used in this book has become popular since Java's release.

Q Can two variables have the same letters but different capitalization, as in highScore and HighScore?

A
Each of the differently capitalized names would be treated as its own variable, so it's possible to use the same name twice in this way. However, it seems likely to cause a lot of confusion when you or someone else is attempting to figure out how the program works. It also increases the likelihood of using the wrong variable name somewhere in your program, which is an error that will not be caught during compilation. Errors like that make it into the finished product and are called logic errors. They must be caught by an attentive programmer during testing.

Quiz

Test your knowledge of variables, expressions, and the rest of the information in this hour by answering the following questions.

Questions

1. What do you call a group of statements contained with an opening bracket and a closing bracket?

(a) A block statement
(b) Groupware
(c) Bracketed statements

2.
A boolean variable is used to store true-or-false values.

(a) True
(b) False
(c) No, thanks. I already ate.

3.
What characters cannot be used to start a variable name?

(a) A dollar sign
(b) Two forward slash marks (//)
(c) A letter

Answers

1. a. The grouped statements are called a block statement or a block.

2. a. True or false are the only answers a boolean variable can store.

3. b. Variables can start with a letter, dollar sign ($), or an underscore character (_). If you started a variable name with two slash marks, the rest of the line would be ignored because the slash marks are used to start a comment line.

Activities

You can review the topics of this hour more fully with the following activities: