Reference Type Variables
What a variable of a class type actually stores: a reference to an object rather than the object itself, and what that means for assignment, aliases, reassignment, and comparing with ==.
Java has two kinds of types. Variables of the primitive types, int, double, and boolean, store their values directly. Every class defines a reference type, and a variable of a reference type holds an object reference, which can be thought of as the memory address of that object. The object itself lives elsewhere in memory. This difference explains why copying a reference variable makes two variables refer to the same object, and why == on references asks "same object?" rather than "same values?"
1Two Kinds of Variables
A primitive variable is a box that holds a value: int count = 7; puts 7 in the box named count. A reference variable is a box that holds a reference, a way of locating an object. String city = "Lisbon"; creates a String object containing "Lisbon" somewhere in memory and puts a reference to it in city.
Objects can be large: a string can hold thousands of characters, and an object can contain many attributes. Storing a compact reference in the variable, instead of a copy of the whole object, lets Java pass objects around efficiently. The cost is that you must keep track of which variables refer to which objects, since several variables can refer to the same one.
| Primitive variable | Reference variable | |
|---|---|---|
| Types | int, double, boolean | Any class: String, Scanner, Lamp |
| What the variable stores | The value itself | A reference to an object (like a memory address) |
Effect of y = x; | Copies the value; the variables stay independent | Copies the reference; both refer to the same object |
Meaning of == | Same value | Same object |
Primitive or Reference?
For each declaration, decide whether the variable is a primitive type or a reference type, and what it stores.
double price = 4.25;String code = "B7";boolean open = true;Lamp desk = new Lamp("green", 80);Scanner input;
- 11 and 3.
doubleandbooleanare primitive types; the variables store 4.25 andtruedirectly. - 22.
Stringis a class, socodeis a reference variable holding a reference to aStringobject containing "B7". - 34.
Lampis a class;deskholds a reference to the newly createdLampobject. - 45.
Scanneris a class, soinputis a reference variable. It has been declared but not yet given an object.
String, is a reference type.2Declaring Reference Variables
A reference variable is declared like any other variable: the type, then the name. The type is a class name: String name;, Lamp desk;, Scanner input;. The declared type determines which objects the variable can refer to; a Lamp variable can hold a reference to a Lamp object but not to a String.
Declaration and object creation are separate steps that are often written together. Lamp desk = new Lamp("green", 80); declares the variable desk on the left, creates a new Lamp object on the right, and stores the reference to that object in desk. Strings are a special case: a string literal such as "Lisbon" creates a String object without writing new.
| Declaration | Variable type | Can refer to |
|---|---|---|
String name; | String | String objects |
Lamp desk; | Lamp | Lamp objects |
Scanner input; | Scanner | Scanner objects |
int total; | int (primitive) | Holds an int value directly, not a reference |
The Reference Must Match the Declared Type
Explain why this does not compile.
public class Lamp
{
private String color;
private int brightness;
public Lamp(String c, int b)
{
color = c;
brightness = b;
}
public void dim()
{
brightness = brightness - 10;
}
public int getBrightness()
{
return brightness;
}
}
- 1Declared type.
porchis declared as aLamp, so it can hold only a reference to aLampobject. - 2The value.
"red"is aStringobject, which is not aLamp. - 3Fix. Create a lamp and store its reference:
Lamp porch = new Lamp("red", 60);.
String cannot be converted to a Lamp. A reference variable's type determines which objects it can refer to.The variable desk is not the lamp; it refers to the lamp. This distinction matters whenever references are copied or reassigned. A helpful habit is to draw reference variables as boxes containing arrows, and objects as separate boxes the arrows point to.
3References as Memory Addresses
A variable of a reference type holds an object reference, which can be thought of as the memory address of that object. An address does not contain the house; it tells you where to find it. When code calls desk.dim(), Java follows the reference stored in desk to the object and runs dim on that object.
Java never shows you the actual address, and you never need it. What matters is the consequence: two variables holding the same reference lead to the same object, exactly as two people holding the same address arrive at the same house. Thinking of references as addresses makes the behavior of assignment, aliases, and == predictable.
The same picture explains method calls with object arguments. When a reference variable is passed to a method, the parameter receives a copy of the reference, so the method can reach the very same object. Primitive arguments, by contrast, give the method a copy of the value, and nothing the method does to its parameter can affect the caller's variable. Both cases follow one rule, call by value; what differs is whether the value being copied is a number or a reference.
The Same Steps With int Variables
Compare with the previous example. Predict the output.
int x = 5;
int y = x;
y = y - 3;
System.out.println(x);
System.out.println(y);
5
2
- 1
int y = x;copies the value 5 intoy. - 2
y = y - 3;changes onlyy, to 2. - 3
xis unaffected and still holds 5 (Figure 2).
Lamp example behaved differently.4Aliases: Two Variables, One Object
Assigning one reference variable to another copies the reference, not the object. After Lamp b = a;, the variables a and b hold the same reference, so they refer to the same object. Two references to the same object are called aliases. Any change made to the object through one alias is visible through the other, because there is only one object to change.
Aliasing is often useful, for example when a method receives a reference to an object it should update. It can also cause surprises when a programmer expects Lamp b = a; to make a copy. To get a separate object with the same values, you must create a new object with new.
Two Variables, One Object
Predict the output.
public class Lamp
{
private String color;
private int brightness;
public Lamp(String c, int b)
{
color = c;
brightness = b;
}
public void dim()
{
brightness = brightness - 10;
}
public int getBrightness()
{
return brightness;
}
}
70
70
- 1One object is created. Only one
newappears, so there is only oneLamp. - 2
Lamp b = a;copies the reference inaintob. Both refer to the same object (Figure 3). - 3
b.dim()changes that object's brightness to 70. - 4Both variables report 70, because both refer to the one object that was dimmed.
Lamp b = a; does not create a second lamp. It creates a second reference to the same lamp. Only new creates a new object. Count the new expressions to count the objects.
5Reassigning a Reference Variable
A reference variable can be given a different reference at any time. a = new Lamp("red", 40); creates a new object and stores its reference in a. Any other variable that referred to the old object, such as an alias b, still refers to the old object; reassigning a changes where a points, nothing else.
Tracing such code is easiest with a table that records which object each variable refers to after every statement. Update a variable's column only when it appears on the left side of an assignment, and update an object's attributes when a method is called through any variable that refers to it.
| Statement | a refers to | b refers to |
|---|---|---|
| Lamp a = new Lamp("white", 80); | white lamp (80) | (not declared) |
| Lamp b = a; | white lamp (80) | white lamp (80) |
| a = new Lamp("red", 40); | red lamp (40) | white lamp (80) |
| a.dim(); | red lamp (30) | white lamp (80) |
Pointing a Variable at a New Object
Predict the output.
public class Lamp
{
private String color;
private int brightness;
public Lamp(String c, int b)
{
color = c;
brightness = b;
}
public void dim()
{
brightness = brightness - 10;
}
public int getBrightness()
{
return brightness;
}
}
30
80
- 1First two lines.
aandbboth refer to the white lamp. - 2
a = new Lamp("red", 40);creates a second object and stores its reference ina.bstill refers to the white lamp (Figure 4). - 3
a.dim()dims the red lamp: 40 → 30. - 4
bstill refers to the white lamp, which was never dimmed: 80.
Reassigning a String Variable
String variables are reference variables too. Predict the output.
String s = "tide";
String t = s;
s = s + "s";
System.out.println(s);
System.out.println(t);
tides
tide
- 1
String t = s;makestan alias of theStringobject "tide". - 2
s = s + "s";builds a brand-newStringobject, "tides", and stores its reference ins. The original object is not modified. - 3
tstill refers to the original "tide".
Lamp variable.After a = new Lamp("red", 40);, the white lamp that a used to refer to is unchanged. Reassignment moves the arrow; it does not modify, copy, or delete the object the arrow used to point to.
6Comparing References With ==
For primitive variables, == compares values. For reference variables, == compares the references themselves: it is true only when both variables refer to the same object. Two separately created objects with identical attribute values are still different objects, so == reports false.
To ask whether two objects hold equal data, a class provides a method for that purpose. For strings, that method is equals: first.equals(second) compares the characters, while first == second only asks whether they are the same object. Using == to compare string contents is a classic mistake.
The two comparisons answer different questions, and both are useful. == answers "are these two variables aliases?", which matters when you need to know whether a change through one will be seen through the other. equals answers "do these objects represent the same value?", which is what most comparisons of strings need.
Same Object or Just Equal Values?
The operator == on reference variables compares the references, that is, whether both variables refer to the same object. Predict each result.
public class Lamp
{
private String color;
private int brightness;
public Lamp(String c, int b)
{
color = c;
brightness = b;
}
public void dim()
{
brightness = brightness - 10;
}
public int getBrightness()
{
return brightness;
}
}
false
true
- 1
a == b. Two separatenewcalls create two objects. Their attribute values match, but they are different objects, so the references differ:false. - 2
a == c.cwas assigneda's reference, so both refer to the same object:true.
== asks whether two references point to the same object, not whether two objects hold equal data.== on references tests identity (same object), not equality of contents. Two lamps with the same color and brightness are not == unless they are the same object. For strings, use equals to compare characters.
Four Habits for Reference Variables
1. Draw Arrows
A reference variable holds an arrow to an object, not the object.
2. Count the news
Each new creates one object; assignment never does.
3. Aliases Share Changes
Two variables with the same reference see the same object.
4. == Means Same Object
Use equals to compare string contents.
A variable of a reference type holds an object reference, which can be thought of as the memory address of that object. Assigning one reference variable to another copies the reference, so both variables refer to the same object and changes made through either are visible through both. Reassigning a reference variable changes only which object that variable refers to. The == operator on references tests whether two variables refer to the same object, while primitive variables store and compare their values directly.