5.13.4. Object References

When a program stores an object in a variable, what it really stores is an object reference, or, more briefly, a reference. You can think of a reference as the place in the computer's memory where the object is stored.

When you get an object in one variable and store it into another, the object is not copied; only the reference is copied. So after

  String x = "peanut butter";
  String y = x;
variables x and y refer to the same string. The string is not copied.

For strings, that is not really important (except for efficiency), since you are not allowed to change a string, once it is created. But most types of objects can be changed. For example, there is a class called StringBuilder in the Java API. It is used for building up strings. Statements

  StringBuilder b = new StringBuilder();
  StringBuilder c = b;
  b.append("robin");
  String s = c.toString();
end with c = "robin". Variables b and c refer to the same object, an it does not matter which variable you use to refer to the object.


The null reference

Java allows you to use a reference, called null, that does not refer to any object. You can store null into any variable whose type is a class. But be careful.

  String s    = null;
  int    slen = s.length();
asks the non-object null to do something, which is not possible. It throws exception NullPointerException.


Copying an object

You can make a copy of an object, with new variables, using method clone For example,

  StringBuilder b = new StringBuilder();
  b.append("robin");
  StringBuilder c = b.clone();
  b.append(" redbreast");
  String bcontent = b.toString();
  String ccontent = c.toString();
ends with bcontent = "robin redbreast" and ccontent = "robin"