Last 30 Days
No notifications
A Java array holds a fixed number of values of one type. Once allocated, its length never changes.
int[] nums = new int[5]; // {0, 0, 0, 0, 0}
int[] xs = {10, 20, 30, 40}; // literal
String[] names = new String[3]; // {null, null, null}nums[0] = 7;
int x = nums[0];
int len = nums.length; // FIELD, not method
for (int i = 0; i < xs.length; i++) System.out.println(xs[i]);
for (int v : xs) System.out.println(v); // foreachint[][] grid = new int[3][4]; // 3 rows × 4 cols
int[][] mat = { {1,2,3}, {4,5,6} };
mat[1][2] = 99;java.util.Arraysimport java.util.Arrays;int[] a = {3, 1, 4, 1, 5};
Arrays.sort(a); // [1,1,3,4,5]
int i = Arrays.binarySearch(a, 4); // 3 (must be sorted)
int[] c = Arrays.copyOf(a, 8); // length 8 (zeros padded)
int[] s = Arrays.copyOfRange(a, 1, 4);
Arrays.fill(a, 0); // [0,0,0,0,0]
String show = Arrays.toString(a); // "[0, 0, 0, 0, 0]"
boolean eq = Arrays.equals(a, b);
For dynamic resize, jump to ArrayList (covered in Collections).
int[] a; // declare
a = new int[5]; // allocate (zero-initialised)int[] b = new int[5]; // declare + allocate
int[] c = {10, 20, 30}; // literal
int[] d = new int[]{10, 20, 30}; // explicit form (needed in returns/args)
String[] words = new String[3]; // [null, null, null]
> Reference-type arrays default to null. Numeric arrays default to 0 (or 0.0). boolean[] defaults to false.
int len = a.length; // FIELD — no parentheses!String uses length() (method), arrays use length (field). Easy to swap by mistake.
Zero-based. Out-of-range access throws ArrayIndexOutOfBoundsException at runtime:
int[] a = {10, 20, 30};
a[3]; // throws ArrayIndexOutOfBoundsException
a[-1]; // also throwsint[] a = {10, 20, 30};// Index access
for (int i = 0; i < a.length; i++) System.out.println(a[i]);
// Foreach (clearest)
for (int x : a) System.out.println(x);
// Index + value (manual)
for (int i = 0; i < a.length; i++) {
System.out.printf("%d -> %d%n", i, a[i]);
}
Java has no true 2D arrays — they're arrays of arrays, which means rows can be different lengths (jagged):
int[][] mat = new int[3][4]; // 3×4 rectangular
mat[0][0] = 1;
int rows = mat.length;
int cols = mat[0].length;int[][] jagged = {
{1, 2},
{3, 4, 5},
{6}
};
for (int[] row : jagged) {
for (int v : row) System.out.print(v + " ");
System.out.println();
}
int[] a = {1, 2, 3, 4, 5};// Shallow copy (whole array, same length)
int[] b = a.clone();
// Resize
int[] bigger = Arrays.copyOf(a, 10); // pads with 0s
int[] slice = Arrays.copyOfRange(a, 1, 4); // [2,3,4]
// Manual / partial copy
int[] dst = new int[5];
System.arraycopy(a, 0, dst, 0, a.length);
> clone() is shallow. For String[][] you'd need to clone each row separately to deep-copy.
java.util.Arrays — The Toolboximport java.util.Arrays;int[] a = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.sort(a); // in-place, dual-pivot quicksort, O(n log n)
Arrays.sort(a, 2, 5); // sort range [2..5)
int idx = Arrays.binarySearch(a, 4); // O(log n) — array MUST be sorted
Arrays.fill(a, 0); // fill all with 0
Arrays.fill(a, 2, 5, -1); // fill range with -1
System.out.println(Arrays.toString(a)); // "[3, 1, 4, 1, 5]"
System.out.println(Arrays.equals(a, b)); // element-wise equality
// 2D
int[][] m = { {1,2}, {3,4} };
System.out.println(Arrays.deepToString(m)); // "[[1, 2], [3, 4]]"
System.out.println(Arrays.deepEquals(m, n));
Integer[] nums = {3, 1, 4, 1, 5};
Arrays.sort(nums); // natural order
Arrays.sort(nums, Comparator.reverseOrder()); // descending
Arrays.sort(strs, Comparator.comparingInt(String::length)); // by length> Note: Arrays.sort on int[] (primitive) → quicksort. On Integer[] (object) → stable mergesort. Different guarantees.
import java.util.Arrays;
import java.util.List;int[] a = {1, 2, 3};
int sum = Arrays.stream(a).sum();
int max = Arrays.stream(a).max().getAsInt();
int[] doubled = Arrays.stream(a).map(x -> x * 2).toArray();
String[] names = {"Asha", "Bishan"};
List<String> list = Arrays.asList(names); // FIXED-SIZE view!
List<String> mutable = new ArrayList<>(Arrays.asList(names)); // resizable copy
> ⚠️ Arrays.asList returns a fixed-size, backing-array-shared list. add/remove throw UnsupportedOperationException. Wrap in new ArrayList<>(...) if you need a real list.
int[] (array) | ArrayList | |
| Size | Fixed | Resizable |
| Type | Primitive or reference | Reference only (boxes) |
| Memory | Compact | Object overhead per element |
| API | length, indexing | size(), add, remove, indexOf |
| Speed | Fastest | Slightly slower (autoboxing) |
Use arrays when size is known + speed matters. Use ArrayList for dynamic data — covered in Collections.
static void reverse(int[] a) {
int i = 0, j = a.length - 1;
while (i < j) {
int t = a[i]; a[i] = a[j]; a[j] = t;
i++; j--;
}
}int[] freq = new int[26];
for (char c : "hello".toCharArray()) freq[c - 'a']++;static int[] twoSumSorted(int[] a, int target) {
int i = 0, j = a.length - 1;
while (i < j) {
int s = a[i] + a[j];
if (s == target) return new int[]{i, j};
if (s < target) i++; else j--;
}
return new int[]{-1, -1};
}| Bug | Fix | |||
a.length() for an array | Arrays use a.length (field). String uses length() (method) | |||
| Trying to grow an array | Allocate a bigger one + copyOf, or switch to ArrayList | |||
Modifying the result of Arrays.asList | Wrap in new ArrayList<>(...) | |||
Arrays.sort then binarySearch on a different array | Both must operate on the same sorted array | |||
a.clone() for 2D arrays expecting deep copy | Clone each row in a loop | |||
== to compare arrays | Use Arrays.equals or Arrays.deepEquals | Cheat-Sheet | Need | Code |
| New zeroed array | new int[n] | |||
| Literal | {1, 2, 3} | |||
| Length | a.length (field) | |||
| 2D | new int[r][c] or { {1,2}, {3,4} } | |||
| Sort | Arrays.sort(a) | |||
| Binary search | Arrays.binarySearch(a, k) (sorted) | |||
| Fill | Arrays.fill(a, val) | |||
Arrays.toString(a), deepToString | ||||
| Copy | Arrays.copyOf(a, len), copyOfRange(a, i, j) | |||
| Equals | Arrays.equals(a, b) | |||
| Sum / max | Arrays.stream(a).sum() / .max() | |||
| Array → List | new ArrayList<>(Arrays.asList(arr)) |
You can now wield Java's fixed-size containers. Next: classes — your own types.