No Java variable represents an object.
String foo; // NOT AN OBJECT
Neither does any Java array contain objects.
String bar[] = new String[100]; // No member is an object.
If you mistakenly think of variables as objects, the actual behavior of the Java language will surprise you.
int
or float
) the variable holds a copy of the value. All copies of a primitive value are indistinguishable; i.e. there is only one int
value for the number one. Primitive values are not objects and they do not behave like objects.null
which means that they point to no object. However, they are not objects and they don’t behave like objects.Variables are not objects in either case, and they don’t contain objects in either case. They may contain references to objects, but that is saying something different.
The examples that follow use this class, which represents a point in 2D space.
public final class MutableLocation {
public int x;
public int y;
public MutableLocation(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object other) {
if (!(other instanceof MutableLocation) {
return false;
}
MutableLocation that = (MutableLocation) other;
return this.x == that.x && this.y == that.y;
}
}
An instance of this class is an object that has two fields x
and y
which have the type int
.
We can have many instances of the MutableLocation
class. Some will represent the same locations in 2D space; i.e. the respective values of x
and y
will match. Others will represent different locations.
MutableLocation here = new MutableLocation(1, 2);
MutableLocation there = here;
MutableLocation elsewhere = new MutableLocation(1, 2);
In the above, we have declared three variables here
, there
and elsewhere
that can hold references to MutableLocation
objects.
If you (incorrectly) think of these variables as being objects, then you are likely to misread the statements as saying:
here
there