<< Chapter < Page | Chapter >> Page > |
Once again, what is a primitive type?
Primitive types are types where the name of the variable evaluates to the value stored in the variable.
What is a reference type?
Reference types in Java are types where the name of the variable evaluates to the address of the location in memory where theobject referenced by the variable is stored.
However, we can think of it that way. Depending on the particular JVM in use, the reference variable may refer to a table in memory where the address of the object is stored. In that case the second level of indirection is handled behind the scenes and we don't have to worry about it.
Why would a JVM elect to implement another level of indirection? Wouldn't that make programs run more slowly?
One reason has to do with the need to compact memory when it becomes highly fragmented. If the reference variables all refer directly to memory locations containing the objects, there may be many reference variables that refer to the same object. If that object is moved for compaction purposes, then the values stored in every one of those reference variables would have to be modified.
However, if those reference variables all refer to a table that has one entry that specifies where the object is stored, then when the object is moved, only the value of that one entry in the table must be modified.
Fortunately, that all takes place behind the scenes and we as programmers don't need to worry about it.
Primitive vs. reference variables
We will discuss this in more detail in a future module. For now, suffice it to say that in Java, a variable is either a primitive type or a reference type,and cannot be both.
Declaring, instantiating, initializing, and manipulating a reference variable
The fragment of code shown in Listing 7 , (which was taken from the program shown in Listing 6 that deals with wrappers) does the following. It
In Listing 7 , the variable named myWrappedData contains a reference to an object of type Double .
Listing 7 . Aspects of using a wrapper class. |
---|
Double myWrappedData = new Double(5.5);
//Code deleted for brevity//Note the use of the doubleValue() method to obtain the
// value of the double wrapped in the Double object.System.out.println
("My wrapped double is " + myWrappedData.doubleValue() ); |
The rules for naming variables are shown in Figure 3 .
Figure 3 . Rules for naming variables. |
---|
|
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?