- Object References
- Wrapper Classes
- Understand object references in Java and how they differ from primitive variables
- Understand strings in Java
- Learn how to create and use arrays
- Understand the primitive wrapper classes and their uses
Primitive variable – stores a data value directly
Reference variable – stores a reference to an object
int i = 13; //i is a primitive variable that holds the value 13 Person p = new Person(); //p is a reference or handle to a Person
With primitives, there is only one thing created in memory.
– i is a memory location that holds the value 13.
With objects, two things are created in memory.
– The object itself, as well as a reference to the object.
– p is a memory location that points to the actual Person object.
– All reference variables are 32-bits in size. They are physical things in memory, like primitive variables.
You can think of a reference variable as a “remote control” for an object, similar to the one for your TV at home.
– It has “operation buttons” on it, and when you push them, “messages” get sent to the object, where the operations are actually performed.
- Recall that with primitives == tests for equality
- Indicates if two values are equal or the same
int x = 3; boolean xIs3 = (x == 3); // true
- With reference variables == tests for identity
– Indicates if two references point to the same object
Turtle t1 = new Turtle(); // brand new Turtle Turtle t2 = new Turtle(); // brand new Turtle Turtle t3 = t2; // t3 refers to same Turtle object as t2
t1 == t2 // false t3 == t2 // true
Indicates that a reference variable doesn’t point to an object
Can test references for null
Turtle t; // no new means no object, t is null boolean tIsNull = (t == null); // true
- Can explicitly initialize to null
Turtle t = null;
- Can’t call methods on null references
– There’s no object to execute the code
– Results in NullPointerException
|Primitive Type||Wrapper Class|