Primitives: the caller's variable never changes
When you call a method, Java copies the value of each argument into the parameter. For primitives the copy is the number itself; for objects and arrays the copy is the reference (the address), so the method can change the object but can never make the caller's variable point somewhere else.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static void fillWith(int[] arr, int value) that sets every element to value, and show that the caller's array changes.
Write static int[] doubledCopy(int[] arr) that returns a new array with every element doubled and leaves the original unchanged. Print both arrays.
Predict, then verify: what does this print? static void change(int[] a, int b) { a[0] = b; b = 100; a = null; } called with int[] arr = {1, 2}; int n = 5; change(arr, n); then printing arr[0] and n.
Explain it without notes
Is Java pass-by-value or pass-by-reference? Give a precise answer an interviewer would accept.
Why can a method change the elements of an array passed to it, but not make the caller's variable point to a new array?
Why doesn't void exclaim(String s) { s = s + "!"; } change the caller's string?
How would you write a method that "swaps" two values for its caller in Java?
What is a defensive copy, and when do you need one?
Expected output
inside addTen: x = 15
after the call: score = 5