← Back to Week 2 Hub

Array Operations

Sort, copy, and pass arrays to methods in Java

Sorting an Integer Array
int[] nums = {42, 17, 85, 3, 61, 28}; Arrays.sort(nums);
nums
 
Warning: Arrays.sort() modifies the original array — it does NOT create a new one.
Sorting a String Array
String[] names = {"Zachary", "Alice", "Natalie"}; Arrays.sort(names);
names
 
Tip: Strings are sorted alphabetically (lexicographically). Uppercase letters sort before lowercase.
Copying Arrays — The Right & Wrong Way
int[] original = {10, 20, 30}; int[] copy = original; // NOT a copy!
original
copy
Array in memory
 
Danger: Using = does NOT copy the array. Both variables point to the same array in memory. Changing one changes both!
Passing Arrays to Methods
public static void printAll(int[] nums) { for (int n : nums) { System.out.println(n); } } // called as: int[] data = {10, 20, 30}; printAll(data);
main()
data
printAll(int[] nums)
nums (same array!)
Points to the same array in memory
 
Key point: Arrays are passed by reference — the method gets the SAME array, not a copy. Changes inside the method affect the original.
Returning Arrays from Methods
public static int[] getScores() { int[] scores = {85, 92, 78}; return scores; } // called as: int[] myScores = getScores();
main()
myScores
getScores()
scores
 
Tip: A method can create an array and return it. The caller receives a reference to the new array. The return type is int[] (not just int).
Quick Reference — Useful Array Methods
Method What It Does Example
Arrays.sort(arr) Sorts the array in ascending order (modifies original) Arrays.sort(nums);
Arrays.toString(arr) Returns a readable string of the array contents System.out.println(Arrays.toString(nums));
System.arraycopy() Copies elements from one array to another (fast) System.arraycopy(src, 0, dest, 0, src.length);
Arrays.fill(arr, val) Fills every element with the given value Arrays.fill(nums, 0);
Arrays.equals(a, b) Compares two arrays element-by-element if (Arrays.equals(a, b)) { ... }
array.length Returns the number of elements (not a method — no parentheses!) int size = nums.length;

Use the tabs to explore sorting, copying, and passing arrays between methods.

← for-each Loop vs for Loop IntelliJ Debugger Walkthrough →