Difference between Java's primitive data type and reference
data type
Primitive data types vs. reference data types
The values of
Primitive data types and
Reference data types are
stored differently
(in Java):
Variables of
Primitive data types
store the actual value
Variables of
Reference data types
store the reference (= address)
of the memory cells where the
actual values are
stored
Fact:
The different way to
store the values of
Primitive data types and
Reference data types give rise to:
different ways
to create variables of
Primitive data types and
Reference data types
Primitive data types:
Defining (creating)
(and using) a variable of
a primitive data type:
int a; // Define (create) the variable
a = 4; // Store value 4 in variable
Graphically:
Reference data types:
Defining (creating)
(and using) a variable of
a reference data type:
int[] a; // Define (create) a REFERENCE variable
a = new int[10]; // Create the actual "object" (big variable)
a[2] = 4; // Store value 4 in some part of the object
Graphically:
First we define (create) the
referencevariable:
Then we create the
actual "object"
(large number of variables):
Notice that:
The variable a now contains
a valid address
(of an "object") !!!
Finally we use
some variable inside the actual object:
Notice that:
The computer uses the
variable name a to
find the start of the object
The computer uses the
index 2 to
locate the
portion of the object
that it needs to use.
Pretest question 4
A variable int x stores:
A reference to an int
An integer value (correct answer)
The identifier "x"
Lots of goodies for every good
Java-slave
Pretest question 5
A variable BankAccount x
stores:
A reference to an object of the
BakAccount class
(correct answer)
An object of the
BakAccount class
The identifier "x"
Even more goodies than a mere
int x
Pretest question 3
Which of the following will always correctly check whether
an object variable obj
contains a
null
reference?
obj.equals(null)
This test if obj variable
and the
nullvariable
are equal
Since null is
not a variable,
there is an error
null == obj
Correct answer
This is the same as:
obj == null
obj = null
The = operation is
the assignment operation
We need to compare
(==)
null.equals(obj)
This test if
nullvariable
and the
objvariable
are equal