assignment Example
We have already seen many assignments of literal values, numbers for example, to variables. This program demonstrates assignment of one variable to another, for exampleThe value of var2 is stored in var1.
The value of var2 is unchanged by the assignment process. The value of var1 has its old value, if it has one, replaced by the new value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Assignment Statement Example
import java.awt.*;
class Stba {
public static void main(String[] args) {
int x0=50, y0=50, x1=150, y1=150;
Color c0 = Color.red, c1 = Color.blue;
ABox b0 = new ABox(c0, x0, y0, 100, 100);
b0.draw();
x0 = x1; y0 = y1;
c0 = c1;
ABox b1 = new ABox(c0, x0, y0, 100, 100);
b1.draw();
}
}
8 Initialization of four primitive variables of type int.
9 Initialization of two reference variables of type Color.
11 A box is constructed using c0, x0, and y0.
These are the variables that are going to be assigned to later.
12 The box is drawn.
14 In these assignment statements the values of x0 and y0 are replaced by the values of x1 and y1 respectively.
x0 and x1 now hold the same value, as do y0 and y1.
15 c0 and c1 are reference variables and therefore reference (point to) objects.
Before the assignment they reference different objects, but after the assignment c0 references to the same object as c1.
17 Another box is constructed using the same variables as for the first box.
18 But the variables have had their values changed and this is reflected when the box is drawn.
