Variables and Assignment Statements
3. Declaration of a Variable
Answer:
Yes. Otherwise it would not be clear what its bits represent.
Remember that the meaning of a bit pattern is determined by its context. It is the data type that
gives the bits in a variable a context.
Declaration of a Variable
The example program uses the variable payAmount
. The statement
long payAmount = 123;
is a declaration of a variable. A declaration of a variable is where a program says that it needs a variable. For our small programs, place declaration statements between the two braces of the main
method.
The declaration gives a name and a data type for the variable. It may also ask that a particular value be placed in the variable. In a high level language (such as Java) the programmer does not need to worry about how the computer hardware
actually does what was asked. If you ask for a variable of type long
, you get it. If you ask for the value 123 to be placed in the variable, that is what happens. Details about bytes, bit patterns, and memory addresses are
up to the Java compiler.
In the example program, the declaration requests an eight-byte section of memory named payAmount
which uses the primitive data type long
for representing values. When the program starts running, the variable
will initially have the value 123 stored in it.
The name for a variable must be a legal Java identifier. (Details in a few pages.)
A variable cannot be used in a program unless it has been declared.
Question 3:
What do you think the program prints on the monitor? (You should be able to figure this out.)