go to previous page   go to home page   go to next page hear noise

Answer:

An assignment statement asks for the computer to perform two steps, in order:

  1. Evaluate the expression on the right of the =
  2. Store the value in the variable on the left of the =

Object Reference

Here is the assignment statement we are considering:

str = new String( "Elementary, my dear Watson!" );

It works like this:

1. Evaluate the expression.

The expression

new String( "Elementary, my dear Watson!" )

is evaluated. This constructs (creates) a new object. The value of this expression is a reference to the new object.

A constructor for an object has the same name as the class and is used with the new operator. Sometimes (as in this example) a constructor requires parameters.

A constructor returns a reference to the object it has created. A reference to an object describes its location in memory. It enables the Java virtual computer to find the object.

2. Store the value in the variable.

In the second step, the reference (the value) is stored in the reference variable:

str = The reference to the string just created

Now whenever the program needs to refer to the object it uses the variable str.

A reference is like a cell phone number. Someone who has your number can send you a message, and ask you to do something, no matter where you are. Think of your boss calling you and sending a message, "Start working on that report!" This is like using an object reference to ask the object to run a method.

Sometimes the variable str is called the "name" of the object. This is a simplification and can lead to confusion if you are not careful. The object, the reference variable, and the reference are three different things.


QUESTION 6:

Are you and your cell phone number different things?