ExerciseWarm-up
Warm-up
Try to write swap
5 minfresher0–4 yrs
One concept, guided. Near-impossible to fail.
What this teaches
- A swap method cannot work in Java, for primitives or for objects
- The object case is the one that disproves pass-by-reference
- Assigning to a parameter only moves the method's own copy of the reference
- Returning values is the Java answer to output parameters
Starter
Starter.java
import java.util.*;
/**
* Warm-up: try to write swap, and watch Java refuse.
*
* Everyone is told the primitive version does not work. Far fewer people have
* actually run the OBJECT version — which is the one that settles the
* pass-by-value argument.
*/
public class Starter {
static void swapPrimitives(int a, int b) {
int t = a;
a = b;
b = t;
}
static void swapObjects(StringBuilder a, StringBuilder b) {
StringBuilder t = a;
a = b;
b = t;
}
public static void main(String[] args) {
int x = 1, y = 2;
swapPrimitives(x, y);
System.out.println("primitives : x=" + x + " y=" + y + " (expected 1, 2 — nothing swapped)");
StringBuilder p = new StringBuilder("first");
StringBuilder q = new StringBuilder("second");
swapObjects(p, q);
System.out.println("objects : p=" + p + " q=" + q);
// TODO 1: was the object result what you expected? If you thought
// objects were "passed by reference", this is the line that disproves
// it. Write down why in a comment.
// TODO 2: make swapObjects appear to work by CHANGING THE OBJECTS
// rather than the references. Hint: StringBuilder has setLength(0),
// append(), and toString().
//
// Then answer: did you swap the variables, or swap the contents of two
// objects the caller still points at? They are not the same thing.
// TODO 3: write the version you would actually ship. It returns
// something instead of using output parameters.
//
// static ??? swapped(StringBuilder a, StringBuilder b)
//
// A record or an array both work. Pick one and say why.
}
}Run it locally:
cd exercises/java/oop/pass-by-value/01-warmup
javac Starter.java -d /tmp/out && java -cp /tmp/out StarterDone when
- You have run a swap on two objects and seen it fail
- You can say why the object case matters more than the primitive case
- You wrote a version that actually works, without output parameters