Reference Types CSCI1302 Lakshmish Ramaswamy Reference Variables Java

Reference Types CSCI-1302 Lakshmish Ramaswamy

Reference Variables • Java supports 8 primitive types • All other types are reference types • Reference variable stores the memory address of where an object resides • Null to indicate the variable is not referencing any object

Reference Example

Operations • Type conversion • Accessing internal field/method (dot operator) • instanceof operator for verifying the type of a stored object • Primitive operations are not allowed

Assignment Operator on References

Objects in Java • Instance of a non-primitive type • Reference variables store the memory location of the objects – Actual objects stored somewhere else – Object variables are a “name” for the memory location

dot Operator • Accessing the internal field of an object • Invoking methods on the object double Area = the. Circle. area(); radius = the. Circle. radius; • Null Pointer exception if variable is storing a null reference

Declaration of Objects Button b; b. set. Label(“No”); p. add(b); Button b; b = new Button(); b. set. Label(“No”); p. add(b); Button b = new Button(“No”); p. add(b);

Garbage Collection • Java destroys all objects that are not referenced • Guarantees that object will be maintained if it is possible to access the object • No guarantees on when an unreferenced object will be destroyed

“=“ Operator • lhs = rhs means the value of rhs will be copied to lhs • For objects memory location will be copied – lhs and rhs refer to the same object Button no. Button = new Button (“no”); Button yes. Button = no. Button; yes. Button. set. Label(“No”); p. add(no. Button); p. add(yes. Button);
- Slides: 10