Reference types, and how they differ¶
โ Java 17 ยท Two Kinds of Data: Primitives and References ยท 2/3
A primitive holds its value. Every other type โ String, Movie, Integer, lists โ is a reference type.
A reference holds an address¶
The Movie object lives on the heap. inception holds its address, like a remote control pointing at a TV.
A reference can also point to nothing:
Calling a method through a null reference stops the program with a NullPointerException.
Two references, one object¶
Assigning a reference copies the address, not the object:
Movie ref1 = new Movie("Inception");
Movie ref2 = ref1; // same object, two remotes
ref1.setTitle("Inception Remastered");
System.out.println(ref2.getTitle()); // Inception Remastered
There is still only one Movie. A change made through ref1 is visible through ref2.
Wrapper classes¶
Each primitive has a matching class: Integer for int, Double for double, Boolean for boolean, and so on. Java converts between them automatically:
Integer views = 1_500_000; // autoboxing: int โ Integer
int count = views; // unboxing: Integer โ int
Side by side¶
| Primitive | Reference | |
|---|---|---|
| Stores | the value itself | the address of an object |
Can be null |
never | yes |
| Has methods | no | yes (length(), equals()โฆ) |
| Default (fields) | 0, false, '\u0000' |
null |
== compares |
values | addresses |
== compares addresses for objects¶
String a = new String("Dune");
String b = new String("Dune");
System.out.println(a == b); // false: two different objects
System.out.println(a.equals(b)); // true: same content
To compare the content of two objects, use equals(). == only tells you whether two references point to the same object.
Choosing between a primitive and a reference type is a design decision. The lab makes those choices for each field of our Movie class.