Storing and Changing Information in a Program - Learning the Basics of Programming - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part II: Learning the Basics of Programming

Hour 5. Storing and Changing Information in a Program

THIS HOUR’S TO-DO LIST:

Image Create a variable.

Image Use different types of variables.

Image Store values in variables.

Image Use variables in mathematical expressions.

Image Store one variable’s value in another variable.

Image Increase and decrease a variable’s value.

In Hour 2, “Writing Your First Program,” you used a variable, a special storage place designed to hold information. The information stored in variables can be changed as a program runs. Your first program stored a string of text in a variable. Strings are only one type of information that can be stored in variables. They also can hold characters, integers, floating-point numbers, and objects.

During this hour, you learn more about using variables in your Java programs.

Statements and Expressions

Computer programs are a set of instructions that tell the computer what to do. Each instruction is called a statement. The following example from a Java program is a statement:

int highScore = 450000;

You can use brackets to group a set of statements together in a Java program. 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 and produce a result. 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 work with expressions during this hour.

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!” The computer needed to remember that text so that the message could be displayed later.

In a Java program, variables are created with a statement that must include two things:

Image The name of the variable

Image The type of information the variable will store

Variables also can include the value of the information being stored.

To see the different types of variables and how they are created, fire up NetBeans and create a new empty Java file with the class name Variable.

Start writing the program by entering the following lines:

package com.java24hours;

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 is used to store integer numbers. You can use the int type to store most of the nondecimal numbers you need in your computer programs. It can hold any integer ranging from around –2.14 billion to 2.14 billion.

Add a blank line after the int tops statement and enter 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.

The float variable type holds decimal numbers of up to 38 figures. The larger double type holds decimal numbers up to 300 figures.


Note

You can use a floating-point variable to store a grade point average, such as 2.25 (to pick my own at the University of North Texas—hi, Professor Wells!). You also can use it to store a number such as 0, which is the percentage chance of getting into a good graduate school with my grade point average, which is why I was available in the job market in 1996 when this publisher was looking for computer book authors.


Characters and Strings

Because the variables you have dealt with so far are numeric, you might have the impression that all variables are used to store 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 symbol. 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 float gradePointAverage line:

char key = 'C';
String productName = "Larvets";

When you are using character values in your program, you must put single quotation marks on both sides of the character value being assigned to a variable. For string values, you must surround them with double quotation marks.

Quotation marks prevent the character or string from being confused with a variable name or another part of a statement. Take a look at the following statement:

String productName = Larvets;

This statement might look like one telling the computer to create a string variable called productName with 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 there is no variable named Larvets, the program fails to compile with an error.)

After you add the char and String statements, your program resembles Listing 5.1. Make any necessary changes and be sure to save the file.

LISTING 5.1 The Variable Program


1: package com.java24hours;
2:
3: class Variable {
4: public static void main(String[] arguments) {
5: int tops;
6: float gradePointAverage;
7: char key = 'C';
8: String productName = "Larvets";
9: }
10: }



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 different from the other types of information you use in variable statements. You learn about this distinction in Hour 6, “Using Strings to Communicate.”


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 discover later in this hour.

This program can be run but produces no output.

Other Numeric Variable Types

The types of variables you have been introduced to thus far are the main ones you use for most of your Java programming. You can call on a few other types of variables in special circumstances.

You can use the first, byte, 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 from –9.22 quintillion to 9.22 quintillion, which is a large enough number to cover everything but government spending.


Caution

The use of underscores in numbers will be flagged as an error in the NetBeans source code editor if the IDE has been set up to use an older version of Java. To make sure this isn’t happening, in the Projects pane, right-click the name of the current project (likely Java24) and choose Properties. The Project Properties dialog opens with Sources chosen in the Categories pane. Check the Source/Binary Format drop-down to make sure it is the current version of Java.


When you are working with large numbers in Java, it can be difficult to see at a glance the value of the number, as in this statement:

long salary = 264400000;

Unless you count the zeros, you probably can’t tell that it’s $264.4 million. Java makes it possible to organize large numbers with underscore (“_”) characters. Here’s an example:

long salary = 264_400_000;

The underscores are ignored, so the variable still equals the same value. They’re just a way to make numbers more human readable.

The boolean Variable Type

Java has a type of variable called boolean that can be used only 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 true-or-false quizzes. However, boolean variables are used in a variety of situations in your programs. The following are some examples of questions that boolean variables can be used to answer:

Image Has the user pressed a key?

Image Is the game over?

Image Is my bank account overdrawn?

Image Do these pants make my butt look fat?

Image Can the rabbit eat Trix?


Note

Boolean numbers are named for George Boole (1815–1864). Boole, a mathematician who was mostly self-taught until adulthood, invented Boolean algebra, which has become a fundamental part of computer programming, digital electronics, and logic. One imagines that he did pretty well on true-false tests as a child.


Booleans are the place to hold the answer to yes/no and true/false questions.

The following statement creates a boolean variable called gameOver:

boolean gameOver = false;

This variable has the starting value of false, so a statement like this could indicate in a game program that the game isn’t over yet. Later, when something happens to end the game, the gameOver variable can be set to true.

Although the two possible Boolean values 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.

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. You can give your variables almost any name you like but should be consistent in how you name them. This section outlines the generally recommended naming method for variables.

Java is case sensitive when it comes to variable names, so you must always capitalize variable names the same way. For example, if the gameOver variable is referred to as GameOver somewhere in the program, an error prevents the program from being compiled.


Note

Variable names aren’t the only aspect of Java that’s case sensitive. Everything else you can give a name to in a program, including classes, packages, and methods, must be referred to using consistent capitalization.


A variable’s name 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 subsequent word a capital letter. For instance, if you want 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 works:

int all-TimeHigh Score;
int all Time High Score;

If you try these variable names in a program, NetBeans responds by flagging the error with the red alert icon alongside the line in the source editor.

Words that are used by the language, such as public, class, true, and false, cannot be the name of variables.

Storing Information in Variables

You can store a value in a variable at the same time that you create the variable in a Java program. You also can put a value in the variable at any time later in the program.

To set a starting value for a variable upon its creation, use the equal sign (=). Here’s an example of creating a double 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 described earlier in this hour.

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. Next, an integer variable called totalMileage is created with the same value as mileage. Both variables have the starting value of 300. In future hours, you learn how 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 use it in another statement. If you don’t, when your program is compiled, you might get an error stating that the variable “may not have been initialized.”


As you’ve learned, Java has similar numeric variables that hold values of different sizes. Both int and long hold integers, but long holds a larger range of possible values. Both float and double carry floating-point numbers, but double is bigger.

You can append a letter to a numeric value to indicate the value’s type, as in this statement:

float pi = 3.14F;

The “F” after the value 3.14 indicates that it’s a float value. If the letter was omitted, Java assumes that 3.14 is a double value.

The letter “L” is used for long integers and “D” for double floating-point values.

Another naming convention in Java is to capitalize every letter in the names of variables that do not change in value. These variables are called constants. The following creates three constants:

final int TOUCHDOWN = 6;
final int FIELDGOAL = 3;
final int PAT = 1;

Because constants never change in value, you might wonder why one ever should be used—you can just use the value assigned to the constant instead. One advantage of using constants is that they make a program easier to understand.

In the preceding three statements, the name of the constant was capitalized. This is not required in Java, but it has become a standard convention among programmers to distinguish constants from other variables.

All About Operators

Statements can use mathematical expressions by employing the operators +, -, *, /, and %. You use these operators to crunch numbers throughout your Java programs.

An addition expression in Java uses the + operator, as in these statements:

double weight = 205;
weight = weight + 10;

The second statement uses the + operator to set the weight variable equal to its current value plus 10. A subtraction expression uses the - operator:

weight = weight - 15;

This expression sets the weight variable equal to its current value minus 15.

A division expression uses the / sign:

weight = weight / 3;

This sets the weight variable to its current value divided by 3.

To find a remainder from a division expression, use the % operator (also called the modulo operator). The following statement finds the remainder of 245 divided by 3:

int remainder = 245 % 3;

A multiplication expression uses the * sign. Here’s a statement that employs a multiplication expression as part of a more complicated statement:

int total = 500 + (score * 12);

The score * 12 part of the expression multiplies score by 12. The full statement multiples score by 12 and then adds 500 to the result. If score equals 20, the result of the expression is that total equals 740: 500 + (20 * 12).

Incrementing and Decrementing a Variable

A common task in programs is changing 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 both of these tasks.

To increment the value of a variable by one, use the ++ operator, as in the following statement:

power++;

This statement adds one to the value stored in the power variable.

To decrement the value of a variable by one, use the -- operator:

rating--;

This statement reduces rating by one.


Note

Confused yet? This is easier than it sounds, if you think back to elementary school when you learned about prefixes. Just as a prefix such as “sub-” or “un-” goes at the start of a word like suburban or unexpected, a prefix operator goes at the start of a variable name. A postfix operator goes at the end.


You also can put the increment and decrement operators in front of the variable name, as in the following statements:

++power;
--rating;

Putting the operator in front of the variable name is called prefixing, and putting it after the name is called postfixing.

The difference between prefixed and postfixed operators becomes important when you use the increment and decrement operators inside an expression.

Consider the following statements:

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 ends up with the value 30 because 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 doesn’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:

int answer = x * 10;
x++;

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.

Consider the following statements:

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;

It’s easy to become exasperated with the ++ and -- operators because they’re not as straightforward as many of the concepts you encounter in this book.

I hope I’m not breaking some unwritten code of Java programmers by telling you this, but 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 like this:

x = x + 1;
y = y - 1;


Note

Back in 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. 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 too will be able to tell jokes like this that are incomprehensible to more than 99 percent of the world’s population.


Incrementing and decrementing are useful shortcuts, but taking the longer route in an expression is fine, too.

Operator Precedence

When you are using an expression with more than one operator, you need to know what order the computer uses as it works out the expression. Consider the following statements:

int y = 10;
x = y * 3 + 5;

Unless you know what order the computer uses when working out the math in these statements, 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.

The following evaluation order is used when working out an expression:

1. Incrementing and decrementing take place first.

2. Multiplication, division, and modulus division occur next.

3. Addition and subtraction follow.

4. Comparisons take place next.

5. The equal sign (=) is used to set a variable’s value.

Because multiplication takes place before addition, you can revisit the previous example and come up with the answer: y is multiplied by 3 first, which equals 30, and then 5 is added. The x variable is set to 35.

Comparisons are 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;

These statements set the number variable equal to 50.

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

int number = 30 + 20;

This expression results in the number variable being set to 50.

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.

Using Expressions

When you were in school, as you worked on a particularly unpleasant math problem, 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 your teachers were right—your math skills come in handy in your computer programming. That’s the bad news.

The good news is that the computer does any math you ask it to do. Expressions are used frequently in your computer programs to accomplish tasks such as the following:

Image Changing the value of a variable

Image Counting the number of times something has happened in a program

Image Using a mathematical formula in a program

As you write computer programs, you 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 NetBeans and create a new Java file with the class name PlanetWeight. This program tracks a person’s weight loss and gain as she travels to other bodies in the solar system. Enter the full text of Listing 5.2 in the source editor. Each part of the program is discussed in turn.

LISTING 5.2 The PlanetWeight Program


1: package com.java24hours;
2:
3: class PlanetWeight {
4: public static void main(String[] arguments) {
5: System.out.print("Your weight on Earth is ");
6: double weight = 178;
7: System.out.println(weight);
8:
9: System.out.print("Your weight on Mercury is ");
10: double mercury = weight * .378;
11: System.out.println(mercury);
12:
13: System.out.print("Your weight on the Moon is ");
14: double moon = weight * .166;
15: System.out.println(moon);
16:
17: System.out.print("Your weight on Jupiter is ");
18: double jupiter = weight * 2.364;
19: System.out.println(jupiter);
20: }
21: }


When you’re done, save the file and it should compile automatically. Run the program with the menu command Run, Run File. The output is shown in the Output pane in Figure 5.1.

Image

FIGURE 5.1 The output of the PlanetWeight program.

As in other programs you have created, the PlanetWeight program uses a main() block statement for all its work. This statement can be broken into the following four sections:

1. Lines 5–7: The person’s weight is set initially to 178.

2. Lines 9–11: Mercury weight loss is calculated.

3. Lines 13–15: Weight loss on the Moon is determined.

4. Lines 17–19: Jupiter weight gain is calculated.


Note

For the sample value, the PlanetWeight application used a weight of 178 pounds, which just happens to be the average weight of a person in North America according to a BMC Health Study. That compares to the average 164-pound Oceanian, 156-pound European, 150-pound Latin American, 134-pound African, and 127-pound Asian.

So if you’re reading this in North America and someone asks you, “Would you like an apple pie with that?” the correct answer to the question is no.


Line 6 creates the weight variable and designates it as a large floating-point variable with double. The variable is given the initial value 178 and used throughout the program to monitor the person’s weight.

The next line is similar to several other statements in the program:

System.out.println(weight);

The System.out.println() command displays a string that is contained within its parentheses. On Line 5, the System.out.print() command displays the text “Your weight on Earth is”. There are several System.out.print() and System.out.println() statements in the program.

The difference between them is that print() does not start a new line after displaying the text, whereas println() does.

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.

You’ve also learned that a trip to the Moon is a particularly effective weight-loss plan.

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 expands your knowledge of String variables and how they are stored and used.

Workshop

Q&A

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

A. No. The programs you create in this book put one statement on each line 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. This line would work just fine in Java:

int x = 12; x = x + 1;

Putting more than one statement on a line makes a program more difficult for humans to understand when they read its source code. For this reason, it is not recommended.

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

A. It’s a naming convention that helps your programming in two ways. First, it makes variables easier to spot among the other elements of a Java program. Second, by following a consistent style in the naming of variables, you eliminate errors that can occur when you use a variable in several places in a program. The style of capitalization used in this book is the one that’s been adopted by most Java programmers over the years.

Q. Can I specify integers as binary values in Java?

A. You can, with a feature introduced in a recent version of Java. Put the characters “0b” in front of the number and follow it with the bits in the value. Since 1101 is the binary form for the number 13, the following statement sets an integer to 13:

int z = 0b0000_1101;

The underscore is just there to make the number more readable. It’s ignored by the Java compiler.

Hexadecimal values can be represented with numbers preceded by “0x”, as in Super Bowl 0x30, in which the Seattle Seahawks defeated the Denver Broncos by a score of 0x2B to 0x8.

Q. What the heck are Larvets?

A. Larvets, the product mentioned in this hour, is a snack made from edible worms that have been killed, dried, and mixed with the same kinds of scrumptious food-like 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 www.hotlix.com or by calling 1-800-EAT-WORM.

Quiz

Test your knowledge of variables, expressions, and the rest of the information in this hour by answering the following 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 and false are the only answers a boolean variable can store.

3. B. Variables can start with a letter, a 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:

Image Expand the PlanetWeight program to track a person’s weight on Venus (90.7% of Earth weight) and his weight on Uranus (88.9% Earth)—and stop snickering because I mentioned Uranus.

Image Create a short Java program that uses an x integer and a y integer and displays the result of x squared plus y squared.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.