1.1. Introduction

In computer programming, a variable is just an alias for a location in memory. Since memory addresses are often written in hexadecimal (e.g. 0x012f47ab), modern programming languages allow programmers to use variables instead of requiring them to remember explicit memory addresses.

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 actual data stored in the memory location;

  • type, the attribute that tells the computer how to interpret the value and how much space is needed to store the value; and

  • name, an attribute that tells the computer the word that we want to use to refer to location in memory where the variable’s value is stored.

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

int x = 17

17

int

x

String s = "Hello"

"Hello"

String

s

Notice the type of the two variables above. The first, int, is a primitive type and the second, String, is a reference type. You can immediately tell that String is a reference type by the fact that it start with a capital letter. These two variables both contain values but they work very differently under the hood. In this chapter, we will demonstrate the important differences between these two types of variables.