next up previous
Next: Initializing a variable Up: Unit 02 Previous: Variable declarations

Assignment

The assignment statement is used to store a value in a variable.


Assignment

Syntax:

variableName = expression;

Semantics:

The variable variableName is assigned the value of the expression on the right hand side of the = symbol. Such a value can be (a reference to) an object, or some data of a different type (see later). After the assignment, the value of a variable stays unchanged till the next assignment.

Example:

line = "java";

The result of the execution of the assignment is that afterward line denotes (the object denoted by) "java".


Example: what is the meaning of the following statement?

s = s.concat("yyy");

The execution of the statement amounts to:

  1. evaluate the expression on the right hand side: i.e., concatenate to the current value of s (e.g., "xxx") the string "yyy", obtaining as result "xxxyyy"
  2. replace the current value of s (i.e., "xxx") with the value that has just been computed (i.e., "xxxyyy")

If the value of s before the execution of the assignment was "xxx", after the assignment the value of s is "xxxyyy".

Note: an assignment is different from an equality test (which we will see in Unit 4).


next up previous
Next: Initializing a variable Up: Unit 02 Previous: Variable declarations