Declaration | Primitive | Object Reference |
---|---|---|
int foo; | X | |
String st; | X | |
boolean flag; | X | |
Object obj; | X |
Look at the example program again. When the statement
System.out.println( str );
is executed, the object referred to by str
is found and its data
is written to the monitor.
When the statement
System.out.println( value );
is executed, the primitive value in the variable value
is used directly.
(It is translated into character form and written to the monitor.)
There are two kinds of variables. When used in an expression (as above) they each behave in a different way:
Characteristics | When used in an expression: | |
---|---|---|
primitive variable | Fixed number of bits. Contains the actual data. | Use the data in the variable. |
reference variable | Contains information on how to find the object. | Use the information in the variable to find the object. |
When you declare a variable, you say what type it is. For example:
String str;
says that str
is a reference variable expected to (later on) contain
a reference to an object of type String.
The declaration
long value;
says that value
is a variable containing the primitive data type long
.
When you compile a program,
the declarations tell the compiler what style of information is kept in each
variable, so the compiler uses each variable in the appropriate way every time
it is mentioned in your program.