Complete the Primitive types vs references exercises before reviewing the solutions.

Review the primitive exercise solution with AP CS Tutor Brandon Horn.

Original code

int x = 5;
int y = 6;
x = y;
y = 7;
System.out.println(x);
System.out.println(y);

Output

6
7

Explanation

Primitive type variables store their values directly. The original value of x is 5.

The statement x = y; (read x is set to y) sets the value of x to a copy of the value of y. When the statement is run, the value of y is 6. The value of x is set to 6. The statement does not link x and y.

The statement y = 7; affects only the value of y. The value of x remains unchanged.

Step by step memory diagram

Step 1

int x = 5;

Memory diagram after Step 1

x: 5

Step 2

int x = 5;
int y = 6;

Memory diagram after Step 2

x: 5
y: 6

Step 3

int x = 5;
int y = 6;
x = y;

Memory diagram after Step 3

x: 6
y: 6

Step 4

int x = 5;
int y = 6;
x = y;
y = 7;

Memory diagram after Step 4

x: 6
y: 7

Step 5

int x = 5;
int y = 6;
x = y;
y = 7;
System.out.println(x);
System.out.println(y);

Memory diagram after Step 5

x: 6
y: 7

Output after Step 5

6
7

Additional classes & objects resources

Comments

Comment on Primitive types vs references exercises