1.2. Variables¶
In Java, a variable is a storage location that has a type and holds one value at a time. Variables declared in code also have names, which let programmers store and retrieve values without knowing where in memory those values are kept.
When we declare a variable in Java, we must provide both a name and a type. Here are two examples of variable declarations:
// variable declarations
int x;
double[] myArray;
Notice that you don't see an equals sign (=) in the code above. The
equals sign is used to assign a value to a variable. The first time
you assign a value to the variable, it is called initializing the
variable.
// variable initializations
x = 7;
myArray = new double[10];
Of course, we could combine declarations and initializations in the following way:
// declaring and initializing variables in a single line
int x = 7;
double[] myArray = new double[5];
You should be able to identify a variable's:
value, the data that the variable currently holds;
type, the attribute that tells the computer how to interpret the value and how much space is needed to store the value; and
name, the identifier that code uses to refer to the variable.
Test Yourself
Take a moment to identify the value, type, and name of the variables declared and initialized below. Before looking ahead, write your answers in your notes.
int x = 17;
String s = "Hello!";
Test Yourself Solution (Don't open until completing the question above)
Did you come up with the answers below?
Declaration/Initialization |
Value |
Type |
Name |
|---|---|---|---|
|
|
|
|
|
a reference to a |
|
|
Notice the types of the two variables above. The first, int, is
a primitive type, and the second, String, is a reference
type. You can tell that String is a reference type because it
is not one of Java's eight primitive types; its capital letter is only
a naming convention. Both variables hold values, but they behave
differently in memory:
As shown in the diagram above, x and s are both local variables
of main, so both appear in the frame for that method call. The value
of x is the int value 17, whereas the value of s is
a reference that refers to a String object on the heap. The number
shown in the box for s and in the object's label identifies that
object; it is not, strictly speaking, a memory address. In this chapter,
we will examine the important differences between these two kinds of
variables.