Java Notes
Common array operations include searching, sorting, copying, and reversing. Java arrays have fixed length, so insertion and deletion require shifting or a new array.
Arrays have a fixed length, but their elements can be read, replaced, searched, copied, sorted, and rearranged. Operations that appear to insert or delete an item require shifting values or creating another array.
Search for a value
Linear search checks each element until it finds the target.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
-1 means “not found” because an array index cannot be negative. break stops the search after the first matching value. Linear search is suitable for small or unsorted arrays and takes O(n) time in the worst case.
Sort with Arrays.sort
The java.util.Arrays class provides utility methods for arrays.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Arrays.sort(marks) changes the existing array into ascending order. Arrays.toString(marks) formats the values clearly for display. Do not expect the original order to remain after sorting.
Copy an array
Assignment does not make a new array; it copies a reference. Use Arrays.copyOf when you need an independent copy.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Changing copy[0] does not change original[0], because copyOf created a separate array object.
Reverse in place
To reverse an array without another full array, swap the values at the two ends and move toward the middle.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Each iteration swaps one pair. The loop stops when the indexes meet, so every value is moved once. This takes O(n) time and O(1) extra space.
Insertion and deletion need shifting
Because an array cannot grow, a logical insertion shifts later values right inside unused capacity. A logical deletion shifts later values left and reduces the number of used positions.
| Operation | What must happen |
|---|---|
| Insert at index | Ensure spare capacity, then shift elements right. |
| Delete at index | Shift later elements left; ignore the final duplicate slot. |
| Add beyond fixed length | Create a larger array or use ArrayList. |
Use ArrayList when a collection must grow and shrink frequently. Use an array when the size is fixed or predictable and indexed access is important.
What to remember
- Search uses a loop;
Arrays.sortsorts an array in place. Arrays.copyOfcreates an independent array;copy = originaldoes not.- Reversing swaps pairs from the two ends.
- Arrays are fixed-length, so real insertion and deletion require shifting or another collection type.
Continue the lesson path