Wednesday, December 10, 2008

Variables and Data

Working with Variables and Data Types

In this chapter, you find out the basics of working with variables in Java. Variables are the key to making Java programs general purpose. For example, the Hello, World! programs in the previous chapter are pretty specific: The only thing they say is, "Hello, World!" But with a variable, you can make this type of program more general. For example, you could vary the greeting, so that sometimes it would say "Hello, World!" and other times it would say "Greetings, Foolish Mortals." Or you could personalize the greeting, so that instead of saying "Hello, World!" it said "Hello, Bob!" or "Hello, Amanda!"

Variables are also the key to creating programs that can perform calculations. For example, suppose you want to create a program that calculates the area of a circle given the circle's radius. Such a program uses two variables: one to represent the radius of the circle, the other to represent the circle's area. The program asks the user to enter a value for the first variable. Then, it calculates the value of the second variable.

Declaring Variables

In Java, you must explicitly declare all variables before using them. This rule is in contrast to some languages-most notably Basic and Visual Basic, which let you use variables that haven't been automatically declared. Allowing you to use variables that you haven't explicitly declared might seem a pretty good idea at first glance-but it's a common source of bugs that result from misspelled variable names. Java requires that you explicitly declare variables so that if you misspell a variable name, the compiler can detect your mistake and display a compiler error.

The basic form of a variable declaration is this:

type name;

Here are some examples:

int x;
String lastName;
double radius;

In these examples, variables named x, lastName, and radius are declared. The x variable holds integer values, the lastName variable holds String values, and the radius variable holds double values. For more information about what these types mean, see the section "Working with Primitive Data Types" later in this chapter. Until then, just realize that int variables can hold whole numbers (such as 5, 1,340, or -34), double variables can hold numbers with fractional parts (such as 0.5, 99.97, or 3.1415), and String variables can hold text values (such as “Hello, World!” or “Jason P. Finch”).


Tip

Notice that variable declarations end with semicolons. That's because a variable declaration is itself a type of statement.


REMEMBER

Variable names follow the same rules as other Java identifiers, as I describe in Book II, Chapter 1. In short, a variable name can be any combination of letters and numerals, but must start with a letter. Most programmers prefer to start variable names with lowercase letters, and capitalize the first letter of individual words within the name. For example, firstName and salesTaxRate are typical variable names.

Declaring two or more variables in one statement

You can declare two or more variables of the same type in a single statement, by separating the variable names with commas. For example:

int x, y, z;

Here, three variables of type int are declared, using the names x, y, and z.


Tip

As a rule, I suggest you avoid declaring multiple variables in a single statement. Your code is easier to read and maintain if you give each variable a separate declaration.

Declaring class variables

A class variable is a variable that any method in a class can access, including static methods such as main. When declaring a class variable, you have two basic rules to follow:

  • You must place the declaration within the body of the class, but not within any of the class methods.

  • You must include the word static in the declaration. The word static comes before the variable type.

The following program shows the proper way to declare a class variable named helloMessage:

public class HelloApp
{
static String helloMessage;

public static void main(String[] args)
{
helloMessage = "Hello, World!";
System.out.println(helloMessage);
}
}

As you can see, the declaration includes the word static and is placed within the HelloApp class body, but not within the body of the main method.


Tip

You don't have to place class variable declarations at the beginning of a class. Some programmers prefer to place them at the end of the class, as in this example:

public class HelloApp
{
public static void main(String[] args)
{
helloMessage = "Hello, World!";
System.out.println(helloMessage);
}

static String helloMessage;
}

Here the helloMessage variable is declared after the main method.

I think classes are easier to read if the variables are declared first, so that's where you see them in this book.

Declaring instance variables

An instance variable is similar to a class variable, but doesn't specify the word static in its declaration. As its name suggests, instance variables are associated with instances of classes. As a result, you can only use them when you create an instance of a class. Because static methods aren't associated with an instance of the class, you can't use an instance variable in a static method-and that includes the main method.

For example, the following program won't compile:

public class HelloApp
{
String helloMessage; // error -- should use static keyword

public static void main(String[] args)
{
helloMessage = "Hello, World!";
System.out.println(helloMessage); // will not compile
}
}

If you attempt to compile this program, you get the following error messages:

C:\Java\HelloApp.java:7: non-static variable helloMessage
cannot be referenced from a static context
helloMessage = "Hello, World!";
^
C:\Java\HelloApp.java:8: non-static variable helloMessage
cannot be referenced from a static context
System.out.println(helloMessage);
^

Both of these errors occur because the main method is static, so it can't access instance variables.

Instance variables are useful whenever you create your own classes. But because I don't cover that until Book III, you won't see many examples of instance methods in the remainder of the chapters in Book II.

Declaring local variables

A local variable is a variable that's declared within the body of a method. Then, you can use the variable only within that method. Other methods in the class aren't even aware that the variable exists.

Here's a version of the HelloApp class in which the helloMessage variable is declared as a local variable:


public class HelloApp
{
public static void main(String[] args)
{
String helloMessage;
helloMessage = "Hello, World!";
System.out.println(helloMessage);
}
}

Note that you don't specify static on a declaration for a local variable. If you do, the compiler generates an error message and refuses to compile your program. Local variables always exist in the context of a method, and they exist only while that method is executing. As a result, whether or not an instance of the class has been created is irrelevant.


Tip

Unlike class and instance variables, a local variable is fussy about where you position the declaration for it. In particular, you must place the declaration prior to the first statement that actually uses the variable. Thus the following program won't compile:

public class HelloApp
{
public static void main(String[] args)
{
helloMessage = "Hello, World!"; // error -- helloMessage
System.out.println(helloMessage); // is not yet declared
String helloMessage;
}
}

When it gets to the first line of the main method, the compiler generates an error message complaining that it can't find the symbol “helloMessage”. That's because it hasn't yet been declared.

Although most local variables are declared near the beginning of a method's body, you can also declare local variables within smaller blocks of code marked by braces. This will make more sense to you when you read about statements that use blocks, such as if and for statements. But here's an example:

if (taxRate > 0)
{
double taxAmount;
taxAmount = subTotal * taxRate;
total = subTotal + total;
}

Here the variable taxAmount exists only within the set of braces that belongs to the if statement

No comments:

Post a Comment