Incremental Java
Declaring Objects Variables

Same Old, Same Old

Declaring object variables looks a lot like declaring primitive variables.
  String str ;
The difference is that an object variable creates a box which can store up to one handle. Initially, there's no handle, so the box is null.

In fact, we can write this out explicitly, as in:

  String str = null ;

Initialization

You can initialize a String variable with a String expression. The only String expressions you should know about are literals such as "slimedog" and concatenation such as "slime" + "dog". For now, that's all you need to know (there are other things you can do with Strings, which we'll talk about some other time).

Here's how an initialization looks:

  String str = "slimedog" ;
Recall that a string like "slimedog" is doing something more sophisticated that you might suspect. It is creating (i.e., constructing) a string (from nowhere). This creates a balloon, which holds the String object, and it also creates a handle to the balloon.

The variable str holds the handle. Thus, object variables aren't really objects. They are boxes that hold a handle to an object. This means that two or more variables can hold a handle to the same object.

Here's an example:

  String str = "slimedog" ;
  String str2 = str ;
  String str3 = str ;
When you see String str2 = str, it evaluates str. But since str is just a handle, this really just makes a copy of the handle. Thus, str, str2, str3 each have a handle, but they have the handle to the same balloon object holding "slimedog".