Arrays
Java arrays are fixed-length, zero-indexed, and covariant. The modern way to work with them: java.util.Arrays for sort/fill/binarySearch, streams for transforms, List.of() when you don’t need mutability.
Arrays the way you actually use them
EXAMPLE
import java.util.Arrays;
import java.util.stream.IntStream;
public class ArrayDemo {
public static void main(String[] args) {
// 1) Declaration
int[] a = new int[5]; // {0,0,0,0,0}
int[] b = { 1, 2, 3, 4, 5 };
String[] c = new String[]{ "a", "b" };
int[][] m = { { 1, 2 }, { 3, 4 } }; // 2-D — array of arrays
// 2) Length
System.out.println(b.length);
// 3) Iterate
for (int x : b) System.out.println(x);
for (int i = 0; i < b.length; i++) System.out.println(i + "=" + b[i]);
// 4) Arrays utility methods
Arrays.sort(b); // in-place
int idx = Arrays.binarySearch(b, 3);
Arrays.fill(a, 1); // {1,1,1,1,1}
int[] copy = Arrays.copyOf(b, 10); // size 10, padded with 0
int[] slice = Arrays.copyOfRange(b, 1, 4); // [b[1], b[2], b[3]]
System.out.println(Arrays.toString(b));
System.out.println(Arrays.deepToString(m));
// 5) Streams — sums, max, filters
int total = Arrays.stream(b).sum();
int max = Arrays.stream(b).max().orElseThrow();
int[] evens = Arrays.stream(b).filter(x -> x % 2 == 0).toArray();
// 6) Build with IntStream
int[] zero99 = IntStream.range(0, 100).toArray();
int[] squares = IntStream.rangeClosed(1, 10).map(x -> x * x).toArray();
// 7) Compare — use Arrays.equals, NOT ==
int[] x = { 1, 2, 3 };
int[] y = { 1, 2, 3 };
System.out.println(x == y); // false — different objects
System.out.println(Arrays.equals(x, y)); // true
System.out.println(Arrays.deepEquals(m, m)); // true
// 8) Convert to / from List
var list = Arrays.asList("a", "b", "c");
String[] back = list.toArray(new String[0]);
// 9) Prefer List.of for immutable + clearer APIs
var ro = List.of(1, 2, 3); // immutable
}
}
Why it matters
List<T> beats T[] in modern Java. Arrays survive for performance hot paths, JNI, and varargs — everywhere else, List and Stream are clearer.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
int[] nums = {1, 2, 3, 4};
for (int n : nums) System.out.println(n);
System.out.println(nums.length);
Try it Yourself »
Discussion
Loading…