Assignment statement

Now we know how to introduce variables into our programs—through declarations—and we know that a variable's value is the state of its instance. How do we change a variable's value, or even create its initial value? We use the assignment statement. This is the second statement we have seen; the first was the variable declaration statement.

Here is an example of the assignment statement:

int die1;  // declares die1 as an int variable
die1 = 1;  // assigns the value 1 to die1

The general form of the assignment statement is

LHS = RHS

where LHS stands for “left-hand side” and RHS stands for “right-hand side.” In the assignment statement above, die1 is the LHS and 1 is the RHS. In between the LHS and the RHS is the assignment operator, =.

The LHS represents a storage location—die1, in the example above—and the RHS represents a value—1, in the example above. The assignment operator causes the value of the RHS to be copied into the instance of (storage location named by) the LHS.

It may be worth emphasizing that assignment is an operation that causes the RHS value to be copied into a storage location, and not a mathematical assertion that two values are equal, even though it looks like that. Java uses the equals sign (=) for assignment, but other languages use := or <-. We think that the latter expresses what assignment does better than =, in that it suggests a value being copied from right to left.

Assigning to Fields in Classes Using “.” (dot) Operator

Let's assume the theDice declaration of earlier:

Dice theDice;

You could assign values to the fields of theDice using the “.” (dot) operator:

theDice.die1 = 6;
theDice.die2 = 6;

The period between “theDice” and “die1” is pronounced “dot”.

Assigning to Elements of Arrays Using Brackets ([])

Let's assume the highScores declaration of earlier:

int[] highScores;

You could assign values to the elements of highScores using brackets ([]):

highScores[0] = 34;
highScores[1] = 30;
highScores[2] = 29;

Assigning to Fields in Elements, or Elements of Fields, or Elements of Elements, or …

Accesses to fields and elements can be chained together. We could assign a value to the top-left square of our Tic Tac Toe board (TicTacToeSquare[][] board) as follows:

board[0][0] = TicTacToeSquare.X;

The dealerHand variable declared as Card[] dealerHand is an array of Card objects. We can set the suit and rank of the first object in the array as follows:

dealerHand[0].suit = Suit.Hearts;
dealerHand[0].rank = Rank.Queen;

Note that the way to refer to the values of an enumerated type is enum-type.enum-type-value.