Assignment Statements

In the following, Counter is an INTEGER variable initialized to zero.

The meaning of the first assignment is computing the sum of the value in Counter and 1, and saves it back to Counter. Since Counter's current value is zero, Counter + 1 is 1+0 = 1 and hence 1 is saved into Counter. Therefore, the new value of Counter becomes 1 and its original value 0 disappears.

The second assignment statement computes the sum of Counter's current value and 3, and saves the result back to Counter. Thus, the new value of Counter is 1+3=4.

The following swaps the values in A and B, with the help of C. That is, after completing the following three assignment statements, A and B have 5 and 3, respectively.

Initially, A and B are initialized to 3 and 5, respectively, while C is uninitialized. The first assignment statement puts A's value into C, making A=3, B=5 and C=3.

The second assignment statements puts B's value into A. This destroys A's original value 3. After this, A = 5, B = 5 and C = 3.

The third assignment statement puts C's value into B. This makes A=5, B=3 and C=3. Therefore, the values in A and B are exchanged.

The following is another possible solution; but, it uses one more variable.

Assignment statements

index

An assignment statement gives a value to a variable. For example,

gives the value 5.

The value of a variable may be changed. For example, if has the value 5, then the assignment statement

will give the value 6.

The general syntax of an assignment statement is

where:

  • the must be declared;
  • the may be a simple name, or an indexed location in an array, or a field (instance variable) of an object, or a static field of a class; and
  • the expression must result in a value that is compatible with the type of the . In other words, it must be possible to cast the expression to the type of the variable.

Examples:

An assignment "statement" is not really a statement (although it is typically used that way), but is an expression. The value of the expression is the value that is assigned to the variable. For example, the expression

sets all of , , and to zero.

One thought on “Assignment Statements

Leave a Reply

Your email address will not be published. Required fields are marked *