An assignment statement has the following basic syntax:
variable = expression;
The assignment operator (=) assigns the value of the expression on the right to the variable.
a = 5;
This is not the same as saying, “a equals five,” but is more akin to, “a receives the value five.”
The expression can be a literal constant value such as 2, 12.25, 't' or it can also be a numeric expression involving operands (variables or constants) and operators.
a = 5 + 2;
b = 6 * a;
The assignment operator returns the value of the expression. Returning values in this way allows for chaining of assignment operators. Chaining is when you have more than one assignment in a statement as shown below.
a = b = 5;
The assignment operator is right-associative. This means that the above statement is really solved in this order:
a = (b = 5);// solved from right to left.
Since (b = 5) returns the integer 5, the value 5 is also assigned to variable a.
and
myPencil = new DrawingTool();
A variable will never actually contain an object, only a reference to an object. In the first statement, primitiveValue
is a primitive type, so the assignment statement puts the data directly into it. In the second statement, myPencil
is an object reference variable (the only other possibility) so a reference to the object is put into that variable. The object reference tells the program where to find an object.
Variable Type |
Information It Contains |
When On the Left of "=" |
primitive |
Contains actual data |
Previous data is replaced with new data |
object |
Contains a reference, i.e. information on how to find the object referred to by the variable |
Old reference is replaced with a new reference |
|
The two types of variables are distinguished by how they are declared. Unless it was declared to be of a primitive type, it is an object reference variable. A variable will not change its declared type.
- Be aware. Because these assignments work differently with primitive data types and with objects, you may experience unexpected behavior. Consider the following:
In this example, pencil will draw a blue line instead of red. This happens because we have only created one object here; we only have one new statement. When we say DrawingTool pen = pencil, all we are doing is assigning the variable name of ‘pen’ to the same object that pencil is already assigned to. This means that both pen and pencil refer to the same DrawingTool object, and what you tell pen to do is also happening to the pencil, because they are the same object. This may be confusing at first, but once you begin to utilize OOP, it will begin to make more sense.