Problem 1
- Test level
- Multiple choice
- No calculator
A robot on a grid reports where it is. What does this code print?
final int ROWS = 4;
int row = 1;
char facing = 'N';
row = ROWS;
int col = row;
facing = 'E';
row = 2;
System.out.print("Row " + row);
System.out.println(" col " + col);
System.out.print("Facing ");
System.out.print(facing);
System.out.println("!");
Answer
Line 1: Row 2 col 4, line 2: Facing E!. The statement int col = row; copies the value 4 into col at that moment; changing row to 2 later does not reach back and change col.
Full solution
Assignment (
=) means: work out the value on the right, then store it in the variable on the left, replacing what was there. It is a one-time copy, not a permanent link.Trace with a table, one row per statement that changes a variable:
statement ROWS row col facing final int ROWS = 4;4 int row = 1;4 1 char facing = 'N';4 1 N row = ROWS;4 4 N int col = row;4 4 4 N facing = 'E';4 4 4 E row = 2;4 2 4 E This is the step most people miss: when
rowbecomes 2,colstays 4. Choice (A) treatscolas linked torow. Choice (B) forgets the last assignment torow.Now the output.
print("Row " + row)writesRow 2and stays on the line;println(" col " + col)addscol 4and ends it. Line 1 isRow 2 col 4. Choice (D) treats everyprintas aprintln.Line 2:
Facingthen the charEthen!, all on one line because only the last call isprintln. The value offacingis'E'by now, so (C) is out.
Where students lose points
Thinking int col = row; ties the two variables together. Assignment copies the current value once. Keep a trace table and update only the variable on the left of each =.

