ExerciseWarm-up
Warm-up
One object, two references
5 minfresher0–4 yrs
One concept, guided. Near-impossible to fail.
What this teaches
- Copying a reference copies the arrow, not the object
- A primitive field lives inside its object, on the heap
- int[] is a heap object — 'primitives are on the stack' is about locals only
Starter
Starter.javaOpen in playground
import java.util.*;
/**
* WARM-UP — 5 minutes. One concept. Hard to fail.
*
* Four variables. Two of them share something; two of them do not.
*
* TASKS
* 1. Predict every println BEFORE running. Write the predictions down.
* 2. Run it.
* 3. Answer, in a comment: how many Counter objects exist at line "END"?
* 4. Answer, in a comment: `total` is an int and so is `counter.value`.
* One of them can be changed by another variable and one cannot.
* What is the actual difference between them?
*/
public class Starter {
static final class Counter {
int value;
}
public static void main(String[] args) {
Counter first = new Counter();
Counter second = first;
second.value = 42;
System.out.println("first.value : " + first.value);
System.out.println("second.value : " + second.value);
System.out.println("same object : " + (first == second));
int total = 7;
int copyOfTotal = total;
copyOfTotal = 42;
System.out.println("total : " + total);
System.out.println("copyOfTotal : " + copyOfTotal);
int[] numbers = {1, 2, 3};
int[] alsoNumbers = numbers;
alsoNumbers[0] = 99;
System.out.println("numbers[0] : " + numbers[0]);
System.out.println("array class : " + numbers.getClass().getName());
// END
// Bonus, once you have the above: `numbers` holds ints, and writing
// through alsoNumbers changed what `numbers` sees. Does that fit the
// rule "primitives live on the stack"? If not, what is the real rule?
}
}Run it locally:
cd exercises/java/jvm/heap-vs-stack/01-warmup
javac Starter.java -d /tmp/out && java -cp /tmp/out StarterDone when
- You predicted every line before running
- A comment says how many Counter objects exist at the end, and why
- A comment explains why copying the int behaved differently from copying the reference
← Back to What lives on the heap and what lives on the stack?