java for dummies. Using the Building Blocks Variables, Values, and Types

Материал готовится, пожалуйста, возвращайтесь позднее

Back in 1946, John von Neumann wrote a groundbreaking paper aboutthe newly emerging technology of computers and computing. Amongother things, he established one fundamental fact: For all their complexity,the main business of computers is to move data from one place to another. Take a number — the balance in a person’s bank account. Move this numberfrom the computer’s memory to the computer’s processing unit. Add a fewdollars to the balance and then move it back to the computer’s memory. Themovement of data . . . that’s all there is; there ain’t no more. Good enough! This chapter shows you how to move around your data.

Using VariablesHere’s an excerpt from a software company’s website:SnitSoft recognizes its obligation to the information technology com-munity. For that reason, SnitSoft is making its most popular applicationsavailable for a nominal charge. For just $5.95 plus shipping and handling,you receive a CD-ROM containing SnitSoft’s premier products. Go ahead. Click the Order Now! link. Just see what happens. You get an orderform with two items on it. One item is labeled $5.95 (CD-ROM), and the otheritem reads $25.00 (shipping and handling). What a rip-off! Thanks toSnitSoft’s generosity, you can pay $30.95 for 10 ten cents’ worth of software.

Using a variableThe code in Listing 6-1 makes use of a variable named amount. A variable isa placeholder. You can stick a number like 5.95 into a variable. After you’veplaced a number in the variable, you can change your mind and put a differ-ent number, like 30.95, into the variable. (That’s what varies in a variable.) Of course, when you put a new number in a variable, the old number is nolonger there. If you didn’t save the old number somewhere else, the oldnumber is gone. Figure 6-2 gives a before-and-after picture of the code in Listing 6-1. When thecomputer executes amount = 5.95, the variable amount has the number5.95 in it. Then, after the amount = amount + 25.00 statement is exe-cuted, the variable amount suddenly has 30.95 in it. When you think about avariable, picture a place in the computer’s memory where wires and transis-tors store 5.95, 30.95, or whatever. In Figure 6-2, imagine that each box is sur-rounded by millions of other such boxes.

Now you need some terminology. (You can follow along in Figure 6-3.) Thething stored in a variable is called a value. A variable’s value can changeduring the run of a program (when SnitSoft adds the shipping and handlingcost, for example). The value stored in a variable isn’t necessarily a number. (You can, for example, create a variable that always stores a letter.) The kindof value stored in a variable is a variable’s type. (You can read more abouttypes in the rest of this chapter and in the next two chapters as well.) There’s a subtle, almost unnoticeable difference between a variable and a vari-able’s name.