How are arrays created and initialized?
Solution and explanation
What an array is
An array is a fixed-size, ordered container of elements of one type, stored in contiguous memory. Arrays are objects in Java: they live on the heap and have a length field. Indexing starts at 0, and access by index is O(1).
Creating arrays
int[] marks = new int[5]; // {0, 0, 0, 0, 0} default values
String[] cities = new String[3]; // {null, null, null}
int[] primes = {2, 3, 5, 7, 11}; // declare + initialise
double[] salaries = new double[]{45000.0, 52000.5};
Default values: 0 for numbers, false for boolean, '\u0000' for char, null for objects.
Reading and looping
System.out.println(primes[0]); // 2
System.out.println(primes.length); // 5 (a field, not a method)
for (int i = 0; i < primes.length; i++) System.out.print(primes[i] + " ");
for (int p : primes) System.out.print(p + " "); // enhanced for
primes[5] throws ArrayIndexOutOfBoundsException.
Useful java.util.Arrays methods
int[] a = {5, 2, 9, 1};
Arrays.sort(a); // [1, 2, 5, 9] dual-pivot quicksort for primitives
int pos = Arrays.binarySearch(a, 5); // 2 (array must be sorted)
int[] copy = Arrays.copyOf(a, 6); // [1, 2, 5, 9, 0, 0]
Arrays.fill(a, -1); // all -1
System.out.println(Arrays.toString(copy)); // printing an array directly shows [I@1b6d3586
boolean same = Arrays.equals(a, copy);
Arrays are references
int[] x = {1, 2, 3};
int[] y = x; // same array
y[0] = 99; // x[0] is also 99
int[] z = x.clone(); // independent copy (shallow for object arrays)
Reading an array from input
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
Summary
Arrays have fixed size, O(1) index access, default values and a length field; use java.util.Arrays for sorting, searching, copying and printing.
