Passing Arrays to Methods
1. Rule (beginner)
Arrays are objects → address-copy (shared!). Method CAN change elements (like objects!). Length fixed, content editable. Perfect for sort/fill helpers!
2. Code — Sort + Fill Change Original!
static void doubleAll(int[] a) {
for (int i = 0; i < a.length; i++) a[i] *= 2; // edits SHARED boxes!
}
static void printAll(int[] a) {
for (int x : a) System.out.print(x + " ");
}
public static void main(String[] args) {
int[] m = {1, 2, 3};
doubleAll(m);
printAll(m); // 2 4 6 (changed! — proof!)
}
Varargs bonus (any count!):
static int sum(int... ns) { int s = 0; for (int n : ns) s += n; return s; }
sum(1,2); sum(1,2,3,4); // flexible!
3. Return Array? Yes!
static int[] first3() { return new int[]{1,2,3}; } // fresh array back!
4. Traps
- Reassign
a = new int[5];inside dies (like objects!). Edit elements to affect caller. arr.length(no()!) inside method for safe loops.- Passing
null→ NPE ona.length(check first!).
5. Exam Points
- Modify-in-method program — 5 marks, very frequent.
- Varargs + return-array — 3 marks, frequent.