References, the call stack and what == compares.
Open the interactive lessons →Core Java and the Runtime Memory Model past questions
Contents
1. Loops, step by step
Some loops look before they leap, and one leaps first.
when a loop body runs, and how nested counters carry over
A ticket gate can check your ticket before you walk through, or let you through and check at the exit. With an invalid ticket the first gate lets nobody in; the second has already let you in once.
A while loop is the first gate: test, then body. A do-while loop is the second: body, then test. A for loop is a while loop with the start value and the step written in its header. The gate picture stops at counting: the loop keeps whatever the body changed.
Why does it matter? When the condition is true at the start, both kinds behave alike. They differ exactly when it is false at the start, which is the case a question likes to set up in an inner loop.
Worked example: A false start
Problem.
n starts at 5 and both loops test n < 5. What prints?
public class Main {
public static void main(String[] args) {
int n = 5;
while (n < 5) {
System.out.println("while body " + n);
n++;
}
do {
System.out.println("do body " + n);
n++;
} while (n < 5);
System.out.println("end " + n);
}
}What is asked.
All lines.
Idea.
Test before the first loop, run the body of the second before testing.
while (n < 5): 5 is not below 5, so the body is skipped.do: the body runs, printingdo body 5, andnbecomes 6.- The test
6 < 5is false, so the loop stops. - The last line prints
end 6.
Answer.
do body 5, then end 6
Common mistake.
Skipping the do body because the condition is already false.
The program prints do body 5 and end 6.
nstarts at 4. What prints?
It printswhile body 4,do body 5,end 6.. Thewhileruns once and leavesnat 5; thedobody still runs once.nstarts at 9. How many lines, and what is the last?
It printsdo body 9andend 10.. Thedobody does not look at the condition first.
Worked example: A counter that remembers
Problem.
k is declared outside both loops. What prints on one line?
public class Main {
public static void main(String[] args) {
int k = 0;
for (int row = 0; row < 3; row++) {
while (k < row * 2) {
System.out.print(k);
k++;
}
System.out.print("|");
}
}
}What is asked.
The line.
Idea.
Keep one row per outer round and carry k forward.
row = 0: the inner test0 < 0is false, so only|is printed.row = 1:kruns while below 2, printing01, then|.row = 2:kis already 2 and runs while below 4, printing23, then|.
Answer.
|01|23|
Common mistake.
Restarting k at 0 in every outer round.
Where the counter lives
Outside
int k = 0;
for (int r = 0; r < 3; r++) {
while (k < r) k++;
}Inside
for (int r = 0; r < 3; r++) {
int k = 0;
while (k < r) k++;
}The difference. The line that declares k has moved.
A variable declared inside a loop body is new in every round; one declared outside keeps its value.
"A for loop body runs at least once" is false. If the condition fails at the start, the body never runs and the step expression never runs either.
2. Arrays and references
Methods get copies; sometimes the copy is an arrow.
what a method receives when you pass an array or a number
Give a friend a copy of your house key. If they paint the wall, your wall is painted. If they throw their key away and cut a key to another house, your key still opens your house.
An array variable is such a key. Passing it to a method copies the key, not the house. The analogy stops at plain numbers: an int variable holds the number itself, so the method gets a separate number.
Why is there no way to move the caller's arrow? The parameter is a new variable inside the method's own memory. Assigning to it changes that variable only.
Worked example: Write, then replace
Problem.
What do the two print lines show?
public class Main {
static void bump(int[] data) {
data[0] = data[0] + 10;
}
static void swapOut(int[] data) {
data = new int[] {99};
data[0]++;
}
public static void main(String[] args) {
int[] v = {1, 2};
bump(v);
System.out.println(v[0]);
swapOut(v);
System.out.println(v[0] + " of " + v.length);
}
}What is asked.
Two lines.
Idea.
Separate writes into the array from assignments to the parameter.
bumpwrites into the shared array, sov[0]becomes 11.swapOutassigns a new array to its parameterdata.- The increment changes the new array only.
vstill refers to the first array: element 11, length 2.
Answer.
11, then 11 of 2
Common mistake.
Believing swapOut replaces v.
Passing an array to a method
vholds a reference to one array object on the heap.- The call copies the reference into
data. Now two names reach one array. - Writing through
datachanges the shared array, so the caller sees 11. - Assigning to
datamoves only that local arrow to a new array.vis not touched. - This write lands in the new array only.
- The method's record is gone.
vstill reaches the first array, which holds 11 and 2.
The program prints 11 and 11 of 2.
swapOutreturns the new array andmainwritesv = swapOut(v);. What is the second line?
It prints100 of 1.. Now the caller itself moves its arrow to the returned array.maincallsbump(v.clone());instead ofbump(v);. What prints?
It prints1and1 of 2..bumpwrites into a separate copy.
Worked example: A number, an alias, a new arrow
Problem.
What are the three values?
public class Main {
static void raise(int x) {
x = x + 1;
}
public static void main(String[] args) {
int score = 4;
raise(score);
int[] p = {4};
int[] q = p;
q[0] = 7;
q = new int[] {0};
System.out.println(score + " " + p[0] + " " + q[0]);
}
}What is asked.
One line.
Idea.
A number is copied; an array arrow is shared until one side moves.
raisechanges its own copy of 4, soscorestays 4.qis an alias ofp; writingq[0] = 7changes the shared array.qthen moves to a new array holding 0.pstill sees 7.
Answer.
4 7 0
Common mistake.
Letting the last assignment to q affect p.
Into the box or move the arrow
Write into it
static void f(int[] d) {
d[0] = 5;
}Reassign
static void f(int[] d) {
d = new int[] {5};
}The difference. An index on the left of = against the bare name.
The caller sees writes into the shared object, never a reassigned parameter.
"clone() gives an independent array" fails for an array of arrays. The copy is only one level deep: both outer arrays still point at the same rows until one is replaced.
A shallow grid copy
public class Main {
public static void main(String[] args) {
int[][] g = { {1, 2}, {3} };
int[][] h = g.clone();
h[0][0] = 50;
h[1] = new int[] {60};
System.out.println(g[0][0] + " " + g[1][0]);
}
}3. Activation records
Every unfinished call keeps its own notes.
the memory each method call gets, and the order calls finish
You are reading a book, stop to look up a word, and while reading the entry stop again to check a symbol. You finish the newest task first and then go back to the one under it. Each paused task needs a bookmark.
A method call is a task and its bookmark is the activation record. The course lists what it holds: parameters, local variables, a control link, a return address and a return-value link. The bookmark picture stops at one point: a record also holds the task's own variables, not only the place.
Why a stack? A caller cannot continue until its callee returns, so the call made last always ends first. That last-in, first-out order is exactly what a stack gives.
Inside one record
| Part | Answers |
|---|---|
| parameters | what was passed in? |
| local variables | what has this call computed? |
| control link | whose record is below mine? |
| return address | where does the caller continue? |
| return-value link | where does my result go? |
Worked example: Two calls deep
Problem.
What prints, and how many records exist at the deepest point?
public class Main {
static int add(int a, int b) {
return a + b;
}
static int twice(int n) {
int r = add(n, n);
return r;
}
public static void main(String[] args) {
System.out.println(twice(6));
}
}What is asked.
The number and the depth.
Idea.
Push at each call, pop at each return.
maincallstwice(6): two records.twicecallsadd(6, 6): three records.addreturns 12 and its record is removed.twicereturnsr, andmainprints 12.
Answer.
12, with at most three records
Common mistake.
Counting only recursive calls as new records.
Records push and pop
mainhas the only record. It is about to calltwice(6).- A new record holds the parameter
n, the localrand the way back tomain. addgets its own record on top.twiceis paused below it.addreturns 12. Its record is popped and the value is stored inr.twicereturns 12 tomain, which prints it. One record remains.
Worked example: Work on the way back
Problem.
sumTo prints after its recursive call. What is the output?
public class Main {
static int sumTo(int n) {
if (n == 0) {
return 0;
}
int below = sumTo(n - 1);
System.out.println("back in " + n);
return below + n;
}
public static void main(String[] args) {
System.out.println("total " + sumTo(3));
}
}What is asked.
All lines.
Idea.
Go down until the stopping case, then print while popping.
sumTo(3)callssumTo(2), thensumTo(1), thensumTo(0), each in a new record with its ownn.sumTo(0)returns 0 without printing.- The record for 1 resumes: it prints
back in 1and returns 1. - Then 2 prints and returns 3; then 3 prints and returns 6.
mainprintstotal 6.
Answer.
back in 1, back in 2, back in 3, total 6
Common mistake.
Printing 3 first because it was called first.
sumTo(3) prints back in 1, back in 2, back in 3, total 6.
- The print moves above the line with the recursive call. In what order do the three lines print?
It printsback in 3,back in 2,back in 1,total 6.. Each call now speaks while the stack is growing. - The
ifthat returns 0 is deleted. How does the program end?
It compiles, then fails withStackOverflowError.. Records are pushed with no call ever returning, until the stack is full.
"A record disappears when its variables are no longer used" is false. It stays until the call returns or an exception leaves the method.
4. Same object or same value
Two things can look alike without being one thing.
what == answers for text and boxed numbers
Two identical bus tickets say the same thing but are two pieces of paper. Two friends reading one poster look at the same piece of paper. "Same words" and "same paper" are different questions.
equals asks about the words. == between objects asks about the paper. Java saves memory by sometimes handing out the same paper: equal string literals are interned. The analogy stops there, because you must know exactly when sharing is guaranteed.
Why only sometimes? A literal is known to the compiler, so one pooled object can serve every use. new String asks for a fresh object. Text joined from a variable is built while the program runs, so it is a new object too.
Worked example: Four ways to ask about tea
Problem.
Predict the four lines.
public class Main {
public static void main(String[] args) {
String a = "tea";
String b = "tea";
String c = new String("tea");
String half = "te";
String d = half + "a";
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a == d);
System.out.println(a.equals(d));
}
}What is asked.
Four boolean values.
Idea.
Draw where each string object comes from.
aandbuse one literal, soa == bistrue.cwas made withnew: another object,false.dwas joined at run time from a variable: another object,false.a.equals(d)compares the letters:true.
Answer.
true, false, false, true
Common mistake.
Answering from the letters alone.
The program prints true, false, false, true.
halfis declaredfinal. What is the third line?
It printstrue.. Afinalvariable with a literal value makeshalf + "a"a constant the compiler can compute and intern.- The third test becomes
a == d.intern(). What is the third line?
It printstrue..intern()returns the pooled object with those letters.
Worked example: Boxes small and large
Problem.
Predict the four lines.
public class Main {
public static void main(String[] args) {
Integer x = 100, y = 100;
Integer p = 500, q = 500;
int raw = 500;
System.out.println(x == y);
System.out.println(p == q);
System.out.println(p.equals(q));
System.out.println(p == raw);
}
}What is asked.
Four boolean values.
Idea.
Small boxes are shared; a plain int forces a number comparison.
- 100 lies between -128 and 127, so both variables get the shared box:
true. - 500 is outside that range; on this JDK two boxes are made:
false. equalscompares the numbers:true.rawis anint, sopis unboxed and the numbers match:true.
Answer.
true, false, true, true
Common mistake.
Concluding from the small case that == compares boxed values.
One declaration, one answer
Two boxes
Integer a = 900;
Integer b = 900;
boolean s = a == b;A box and a number
Integer a = 900;
int b = 900;
boolean s = a == b;The difference. The declared type of b.
Two references compare identity; a reference and a primitive compare values.
A test with small numbers proves nothing about large ones. The language guarantees shared boxes from -128 to 127; outside that range it promises nothing, and the default on this JDK gives separate objects.