Chapter 6

Using the Building Blocks: Variables, Values, and Types

IN THIS CHAPTER

check Declaring variables

check Assigning values to variables

check Working with numbers

check Using Java types

Back in 1946, John von Neumann wrote a groundbreaking paper about the newly emerging technology of computers and computing. Among other 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 number from the computer’s memory to the computer’s processing unit. Add a few dollars to the balance and then move it back to the computer’s memory. The movement of data … that’s all there is; there ain’t no more.

Good enough! This chapter shows you how to move your data around.

Using Variables

Here’s an excerpt from a software company’s website:

SnitSoft recognizes its obligation to the information technology community. For that reason, SnitSoft is making its most popular applications available for a nominal charge. For just $5.95 plus shipping and handling, you receive a flash drive containing SnitSoft’s premier products.

Go ahead. Click the Order Now! link. Just see what happens. You get an order form with two items on it. One item is labeled $5.95 (Flash drive), and the other item reads $25.00 (Shipping and handling). What a rip-off! Thanks to SnitSoft’s generosity, you can pay $30.95 for ten cents’ worth of software.

Behind the scenes of the SnitSoft web page, a computer program does some scoundrel’s arithmetic. The program looks something like the code in Listing 6-1.

LISTING 6-1 SnitSoft’s Grand Scam

class SnitSoft {

public static void main(String args[]) {
double amount;

amount = 5.95;
amount = amount + 25.00;

System.out.print("We will bill $");
System.out.print(amount);
System.out.println(" to your credit card.");
}
}

When I run the Listing 6-1 code on my own computer (not on the SnitSoft computer), I get the output shown in Figure 6-1.

image

FIGURE 6-1: Running the code from Listing 6-1.

Using a variable

The code in Listing 6-1 makes use of a variable named amount. A variable is a placeholder. You can stick a number like 5.95 into a variable. After you’ve placed a number in the variable, you can change your mind and put a different 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 no longer there. If you didn’t save the old number somewhere else, the old number is gone.

Figure 6-2 gives a before-and-after picture of the code in Listing 6-1. When the computer executes amount = 5.95, the variable amount has the number 5.95 in it. Then, after the amount = amount + 25.00 statement is executed, the variable amount suddenly has 30.95 in it. When you think about a variable, picture a place in the computer’s memory where wires and transistors store 5.95, 30.95, or whatever. In Figure 6-2, imagine that each box is surrounded by millions of other such boxes.

image

FIGURE 6-2: A variable (before and after).

Now you need some terminology. (You can follow along in Figure 6-3.) The thing stored in a variable is called a value. A variable’s value can change during the run of a program (when SnitSoft adds the shipping and handling cost, 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 kind of value stored in a variable is a variable’s type. (You can read more about types in the rest of this chapter and in the next two chapters.)

image

FIGURE 6-3: A variable, its value, and its type.

technicalstuff There’s a subtle, almost unnoticeable difference between a variable and a variable’s name. Even in formal writing, I often use the word variable when I mean variable name. Strictly speaking, amount is the variable name, and all the memory storage associated with amount (including the value and type of amount) is the variable itself. If you think this distinction between variable and variable name is too subtle for you to worry about, join the club.

Every variable name is an identifier — a name that you can make up in your own code (for more about this topic, see Chapter 4). In preparing Listing 6-1, I made up the name amount.

Understanding assignment statements

The statements with equal signs in Listing 6-1 are called assignment statements. In an assignment statement, you assign a value to something. In many cases, this something is a variable.

You should get into the habit of reading assignment statements from right to left. For example, the first assignment statement in Listing 6-1 says, “Assign 5.95 to the amount variable.” The second assignment statement is just a bit more complicated. Reading the second assignment statement from right to left, you get “Add 25.00 to the value that’s already in the amount variable, and make that number (30.95) be the new value of the amount variable.” For a graphic, hit-you-over-the-head illustration of this, see Figure 6-4.

image

FIGURE 6-4: Reading an assignment statement from right to left.

remember In an assignment statement, the thing being assigned a value is always on the left side of the equal sign.

To wrap or not to wrap?

The last three statements in Listing 6-1 use a neat trick. You want the program to display just one line on the screen, but this line contains three different things:

  • The line starts with We will bill $.
  • The line continues with the amount variable’s value.
  • The line ends with to your credit card.

These are three separate things, so you put these things in three separate statements. The first two statements are calls to System.out.print. The last statement is a call to System.out.println.

Calls to System.out.print display text on part of a line and then leave the cursor at the end of the current line. After executing System.out.print, the cursor is still at the end of the same line, so the next System.out.whatever can continue printing on that same line. With several calls to print capped off by a single call to println, the result is just one nice-looking line of output, as Figure 6-5 illustrates.

image

FIGURE 6-5: The roles played by System.out.print and System.out.println.

remember A call to System.out.print writes some things and leaves the cursor sitting at the end of the line of output. A call to System.out.println writes things and then finishes the job by moving the cursor to the start of a brand-new line of output.

What Do All Those Zeros and Ones Mean?

Here’s a word:

gift

The question for discussion is, what does that word mean? Well, it depends on who looks at the word. For example, an English-speaking reader would say that gift stands for something one person bestows upon another in a box covered in bright paper and ribbons:

Look! I’m giving you a gift!

But in German, the word gift means “poison:”

Let me give you some gift, my dear.

And in Swedish, gift can mean either “married” or “poison:”

As soon as they got gift, she slipped a gift into his drink.

Then there’s French. In France, there’s a candy bar named “Gift”:

He came for the holidays, and all he gave me was a bar of Gift.

What do the letters g-i-f-t really mean? Well, they don’t mean anything until you decide on a way to interpret them. The same is true of the zeros and ones inside a computer’s circuitry.

Take, for example, the sequence 01001010. This sequence can stand for the letter J, but it can also stand for the number 74. That same sequence of zeros and ones can stand for 1.0369608636003646×10–43. And when interpreted as screen pixels, the same sequence can represent the dots shown in Figure 6-6. The meaning of 01001010 depends entirely on the way the software interprets this sequence.

image

FIGURE 6-6: An extreme close-up of eight black-and-white screen pixels.

Types and declarations

How do you tell the computer what 01001010 stands for? The answer is in the concept called type. The type of a variable describes the kinds of values that the variable is permitted to store.

In Listing 6-1, look at the first line in the body of the main method:

double amount;

This line is called a variable declaration. Putting this line in your program is like saying, “I’m declaring my intention to have a variable named amount in my program.” This line reserves the name amount for your use in the program.

In this variable declaration, the word double is a Java keyword. This word double tells the computer what kinds of values you intend to store in amount. In particular, the word double stands for numbers between –1.8×10308 and 1.8×10308. That’s an enormous range of numbers. Without the fancy ×10 notation, the second of these numbers is

180000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000.0

If the folks at SnitSoft ever charge that much for shipping and handling, they can represent the charge with a variable of type double.

What’s the point?

More important than the humongous range of the double keyword’s numbers is the fact that a double value can have digits to the right of the decimal point. After you declare amount to be of type double, you can store all sorts of numbers in amount. You can store 5.95, 0.02398479, or –3.0. In Listing 6-1, if I hadn’t declared amount to be of type double, I wouldn’t have been able to store 5.95. Instead, I would have had to store plain old 5 or dreary old 6, without any digits beyond the decimal point.

For more info on numbers without decimal points, see Chapter 7.

technicalstuff This paragraph deals with a really picky point, so skip it if you’re not in the mood. People often use the phrase decimal number to describe a number with digits to the right of the decimal point. The problem is, the syllable “dec” stands for the number 10, so the word decimal implies a base-10 representation. Because computers store base-2 (not base-10) representations, the word decimal to describe such a number is a misnomer. But in this book, I just can’t help myself. I’m calling them decimal numbers, whether the techies like it or not.

tryitout Here are some things for you to try:

NUMBER CRUNCHING

Change the number values in Listing 6-1, and run the program with the new numbers.

VARYING A VARIABLE

In Listing 6-1, change the variable name amount to another name. Change the name consistently throughout the Listing 6-1 code. Then run the program with its new variable name.

USING UNDERSCORES

Modify the code in Listing 6-1 so that shipping and handling costs 1 million dollars. Use 1_000_000.00 (with underscores) to represent the million-dollar amount.

MORE INFORMATION, PLEASE

Modify the code in Listing 6-1 so that it displays three values: the original price of the flash drive, the cost of shipping and handling, and the combined cost.

Reading Decimal Numbers from the Keyboard

I don’t believe it! SnitSoft is having a sale! For one week only, you can get the SnitSoft flash drive for the low price of just $5.75! Better hurry up and order one.

No, wait! Listing 6-1 has the price fixed at $5.95. I have to revise the program.

I know. I’ll make the code more versatile. I’ll input the amount from the keyboard. Listing 6-2 has the revised code, and Figure 6-7 shows a run of the new code.

image

FIGURE 6-7: Getting the value of a double variable.

LISTING 6-2 Getting a Double Value from the Keyboard

import java.util.Scanner;

class VersatileSnitSoft {

public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
double amount;

System.out.print("What’s the price of a flash drive? ");
amount = keyboard.nextDouble();
amount = amount + 25.00;

System.out.print("We will bill $");
System.out.print(amount);
System.out.println(" to your credit card.");

keyboard.close();
}
}

warning Grouping separators vary from one country to another. The run shown in Figure 6-7 is for a computer configured in the United States where 5.75 means “five and seventy-five hundredths.” But the run might look different on a computer that’s configured in what I call a “comma country” — a country where 5,75 means “five and seventy-five hundredths.” If you live in a comma country and you type 5.75 exactly as it’s shown in Figure 6-7, you probably get an error message (an InputMismatchException). If so, change the number amounts in your file to match your country’s number format. When you do, you should be okay.

Though these be methods, yet there is madness in ’t

Notice the call to the nextDouble method in Listing 6-2. Over in Listing 5-1, in Chapter 5, I use nextLine; but here in Listing 6-2, I use nextDouble.

In Java, each type of input requires its own, special method. If you’re getting a line of text, then nextLine works just fine. But if you’re reading stuff from the keyboard and you want that stuff to be interpreted as a number, you need a method like nextDouble.

To go from Listing 6-1 to Listing 6-2, I added an import declaration and some stuff about new Scanner(System.in). You can find out more about these things by reading the “Getting numbers, words, and other things” section in Chapter 5. (You can find out even more about input and output by visiting Chapter 13.) And more examples (more keyboard.nextSomething methods) are in Chapters 7 and 8.

Methods and assignments

Note how I use keyboard.nextDouble in Listing 6-2. The call to method keyboard.nextDouble is part of an assignment statement. If you look in Chapter 5 at the section on how the EchoLine program works, you see that the computer can substitute something in place of a method call. The computer does this in Listing 6-2. When you type 5.75 on the keyboard, the computer turns

amount = keyboard.nextDouble();

into

amount = 5.75;

(The computer doesn’t really rewrite the code in Listing 6-2. This amount = 5.75 line simply illustrates the effect of the computer’s action.) In the second assignment statement in Listing 6-2, the computer adds 25.00 to the 5.75 that’s stored in amount.

Some method calls have this substitution effect, and others (like System.out.println) don’t. To find out more about this topic, see Chapter 19.

Variations on a Theme

In Listing 6-1, it takes two lines to give the amount variable its first value:

double amount;
amount = 5.95;

You can do the same thing with just one line:

double amount = 5.95;

When you do this, you don’t say that you’re “assigning” a value to the amount variable. The line double amount=5.95 isn’t called an “assignment statement.” Instead, this line is called a declaration with an initialization. You’re initializing the amount variable. You can do all sorts of things with initializations, even arithmetic:

double gasBill = 174.59;
double elecBill = 84.21;
double H2OBill = 22.88;
double total = gasBill + elecBill + H2OBill;

Moving variables from place to place

It helps to remember the difference between initializations and assignments. For one thing, you can drag a declaration with its initialization outside of a method:

//This is okay:
class SnitSoft {
static double amount = 5.95;

public static void main(String args[]) {
amount = amount + 25.00;

System.out.print("We will bill $");
System.out.print(amount);
System.out.println(" to your credit card.");
}
}

You can’t do the same thing with assignment statements (see the following code and Figure 6-8):

//This does not compile:
class BadSnitSoftCode {
static double amount;

amount = 5.95; //Misplaced statement

public static void main(String args[]) {
amount = amount + 25.00;

System.out.print("We will bill $");
System.out.print(amount);
System.out.println(" to your credit card.");
}
}

image

FIGURE 6-8: A failed attempt to compile BadSnitSoftCode.

You can’t drag statements outside of methods. (Even though a variable declaration ends with a semicolon, a variable declaration isn’t considered to be a statement. Go figure!)

The advantage of putting a declaration outside of a method is illustrated in Chapter 17. While you wait impatiently to reach that chapter, notice how I added the word static to each declaration that I pulled out of the main method. I had to do this because the main method’s header has the word static in it. Not all methods are static. In fact, most methods aren’t static. But whenever you pull a declaration out of a static method, you have to add the word static at the beginning of the declaration. All the mystery surrounding the word static is resolved in Chapter 18.

Combining variable declarations

The code in Listing 6-1 has only one variable (as if variables are in short supply). You can get the same effect with several variables:

class SnitSoftNew {

public static void main(String args[]) {
double flashDrivePrice;
double shippingAndHandling;
double total;

flashDrivePrice = 5.95;
shippingAndHandling = 25.00;
total = flashDrivePrice + shippingAndHandling;

System.out.print("We will bill $");
System.out.print(total);
System.out.println(" to your credit card.");
}
}

This new code gives you the same output as the code in Listing 6-1. (Refer to Figure 6-1.)

The new code has three declarations — one for each of the program’s three variables. Because all three variables have the same type (the type double), I can modify the code and declare all three variables in one fell swoop:

double flashDrivePrice, shippingAndHandling, total;

Which is better — one declaration or three declarations? Neither is better. It’s a matter of personal style.

You can even add initializations to a combined declaration. When you do, each initialization applies to only one variable. For example, with the line

double flashDrivePrice, shippingAndHandling = 25.00, total;

the value of shippingAndHandling becomes 25.00, but the variables flashDrivePrice and total get no particular value.

tryitout Would you like some practice with this section’s concepts? You got it!

TIP THE PARKING ATTENDANT

An online blog advises a $2 tip when a parking attendant fetches your car in a New York City garage. Write a program like the one Listing 6-2. When the program runs, you type the garage’s posted price for parking your car. The program tells you how much you’ll pay after adding the $2 tip.

DOUBLE PRICE

Modify the code in Listing 6-2 so that, whatever a flash drive normally costs, the program charges twice that amount. In other words, the price for a $5 flash drive ends up being $10, and the price for a $100 flash drive becomes $200.

Experimenting with JShell

The programs in this book all begin with the same old tiresome refrain:

class SomethingOrOther {

public static void main(String args[]) {

Retyping this boilerplate code into Eclipse’s editor can be annoying, especially when your goal is to test the effect of executing a few simple statements. To fix this problem, the stewards of Java came up with a new tool in Java 9. They call it JShell.

When you use JShell, you hardly ever type an entire program. Instead, you type a Java statement, and then JShell responds to your statement, and then you type a second statement, and then JShell responds to your second statement, and then you type a third statement, and so on. A single statement is enough to get a response from JShell.

JShell is only one example of a language’s Read Evaluate Print Loop (REPL). Many programming languages have REPLs and, with Java 9, the Java language finally has a REPL of its own.

Launching the JShell program

To run JShell, make sure you have Java 9 (or a higher version of Java when it becomes available) on your computer.

To launch JShell on a Windows computer

  1. Open a Command Prompt window.

    In Windows 7: Press Win+R, and then type cmd, and then press Enter.

    In Windows 8: On the Start screen, press Win+Q. In the resulting search field, type command prompt, and then press Enter.

    In Windows 10: Choose Start ⇒   Windows System ⇒   Command Prompt.

  2. In the Command Prompt window, type the following commands:

    cd "Program FilesJava"
    dir jdk*

    tip On some computers, you might have better luck typing cd "Program Files (x86)Java" for the first of the two commands. Whatever works!

    The Command Prompt window responds by listing some directory names.

  3. In the Command Prompt window’s response, look for a directory named jdk-9, or something like that.

    Directories whose names start with jdk1.8 or lower won’t work. You must have Java 9 or higher installed in order to run JShell.

    In the next step, I assume that you’ve found a directory named jdk-9. If your directory has a different name, adjust your typing to match that name.

  4. In the Command Prompt window, type the following commands:

    cd jdk-9in
    jshell

    If all goes well, the Command Prompt window displays the JShell> prompt. That’s how you know that you’ve successfully launched  JShell.

To launch JShell on a Mac

  1. Press Command+spacebar, and then type Terminal, and then press Enter.

    As a result, your computer’s Terminal application starts running.

  2. In the Terminal application’s window, type the following commands:

    cd /Library/Java/JavaVirtualMachines
    dir jdk*

    The Terminal application responds by listing some directory names.

  3. In the Terminal application’s response, look for a directory named jdk-9.jdk, or something like that.

    Directories whose names start with jdk1.8 or lower won’t work. You must have Java 9 or higher installed in order to run  JShell.

    In the next step, I assume that you’ve found a directory named jdk-9.jdk. If your directory has a different name, adjust your typing to match that name.

  4. In the Terminal application’s window, type the following commands:

    cd jdk-9.jdk/Contents/Home/bin
    ./jshell

    If all goes well, the Terminal application displays the JShell> prompt. That’s how you know that you’ve successfully launched  JShell.

Using JShell

In Figure 6-9, I use JShell to experiment with this chapter’s Java concepts.

image

FIGURE 6-9: An intimate conversation between me and JShell.

When you run JShell, the dialogue goes something like this:

jshell> You type a statement
JShell responds

jshell> You type another statement
JShell responds

For example, in Figure 6-9, I type double amount and then press Enter. JShell responds by displaying

amount ==> 0.0

Then I type amount = 5.95, and JShell responds with

amount ==> 5.95

And then, when I type amount = amount + 25.00, JShell comes back with a friendly

amount ==> 30.95

Here are a few things to notice about JShell:

  • You don’t have to type an entire Java program.

    Typing a few statements such as

    double amount
    amount = 5.95
    amount = amount + 25.00

  • does the trick. It’s like running the code snippet in Listing 4-1 (except that Listing 4-1 doesn’t declare amountInAccount to be a double).
  • In JShell, semicolons are (to some extent) optional.

    In Figure 6-9, I don’t bother to end any lines with semicolons.

  • JShell responds immediately after you type each line.

    After I declare amount to be double, JShell responds by telling me that the amount variable has the value 0.0. After I type amount = amount + 25.00, JShell tells me that the new value of amount is 30.95.

Figure 6-10 illustrates a few more of JShell’s nice features.

  • You can ask JShell for the value of an expression.

    You don’t have to assign the expression’s value to a variable. For example, in Figure 6-10, I type

    gasBill + elecBill

    JShell responds by telling me that the value of gasBill + elecBill is 258.8. JShell makes up a temporary name for that value. In Figure 6-10, the name happens to be $3.

  • You can even get answers from JShell without using variables.

    In Figure 6-10, I ask for the value of 42 + 7, and JShell generously answers with the value 49. JShell makes up the temporary name $4 for that value 49. So, on the next line in Figure 6-10, I ask for the value of $4 +1, and JShell gives me the answer 50.

image

FIGURE 6-10: Using JShell to evaluate expressions.

tip While you’re running JShell, you don’t have to retype commands that you’ve already typed. If you press the up-arrow key once, JShell shows you the command that you typed most recently. If you press the up-arrow key twice, JShell shows you the next-to-last command that you typed. And so on. When JShell shows you a command, you can use the left- and right-arrow keys to move to any character in the middle of the command. You can modify characters in the command. Finally, when you press Enter, JShell executes your newly modified command.

To end your run of JShell, you type /exit (starting with a slash). But /exit is only one of many commands you can give to JShell. To ask JShell what other kinds of commands you can use, type /help.

With JShell, you can test your statements before you put them into a full-blown Java program. That makes JShell a truly useful tool.

FUN WITH JSHELL

tryitout Launch the JShell application on your computer. Type the following statements, one after another, into the JShell application, and watch how JShell responds:

jshell> double bananaCalories = 100.0

jshell> double appleCalories = 95.0

jshell> double dietSodaCalories = 0.0

jshell> double cheeseburgerCalories = 500.0

jshell> bananaCalories + appleCalories +
…> dietSodaCalories + cheeseburgerCalories

Notice that, in JShell, a statement can straddle two or more lines. After typing the first part of a statement

bananaCalories + appleCalories +

you press Enter. Then, on the next line, JShell doesn’t display its usual jshell> prompt. Instead, JShell displays …>, which indicates that you should continue typing more of the same statement.

Keep JShell running in preparation for the next experiment.

MOVING WITHIN JSHELL

In the previous experiment, you entered the calorie counts for four food items. But because you performed that experiment, you’ve revised your estimate of the number of calories in a cheeseburger.

With JShell still running, press your keyboard’s up-arrow key until you see the statement

double cheeseburgerCalories = 500.0

Then press the left-arrow key until the cursor is next to the 5 digit. Press your keyboard’s Backspace or Delete key to get rid of the 5 digit, and then type a 7 digit in its place. Now the statement reads as follows:

double cheeseburgerCalories = 700.0

Press Enter to confirm that you want JShell to execute that revised statement.

With the value of cheeseburgerCalories changed to 700.0, use your keyboard’s up arrow and down arrow to make JShell sum up the calorie counts a second time:

jshell> bananaCalories + appleCalories +
…> dietSodaCalories + cheeseburgerCalories

Don’t retype the variable names. Let your arrow keys do the work!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.134.130