One-Dimensional Arrays

Creating and using single-dimension arrays

Interview Relevant: Array manipulation is common in coding tests
7 min read

What is an Array?

An array is a fixed-size, ordered collection of elements of the same data type. Arrays provide fast random access to elements using indices.

Array Characteristics

  • Fixed size: Cannot grow or shrink after creation
  • Zero-indexed: First element is at index 0
  • Homogeneous: All elements must be same type
  • Contiguous memory: Elements stored consecutively

🔑 Key Point: Arrays in Java are objects! They inherit from Object class and have a length property (not method).

Default Values

  • int, short, byte, long: 0
  • float, double: 0.0
  • boolean: false
  • char: '\u0000'
  • Object references: null

⚠️ ArrayIndexOutOfBoundsException: Accessing index < 0 or >= length throws this runtime exception!

Code Examples

Array declaration, creation, and access

java
1// Declaration and creation
2int[] numbers;              // Declaration (preferred)
3int numbers2[];             // Also valid (C-style)
4
5numbers = new int[5];       // Create array of 5 integers
6
7// Declaration + creation in one line
8int[] scores = new int[10];
9
10// Declaration + initialization
11int[] values = {1, 2, 3, 4, 5};       // Array literal
12String[] fruits = {"Apple", "Banana", "Cherry"};
13
14// Access and modify
15System.out.println(values[0]);        // 1 (first element)
16System.out.println(values[4]);        // 5 (last element)
17values[2] = 100;                      // Modify third element
18
19// Array length
20System.out.println(values.length);    // 5 (note: property, not method!)

Different ways to iterate over arrays

java
1// Iteration methods
2int[] arr = {10, 20, 30, 40, 50};
3
4// Method 1: Traditional for loop (when index needed)
5for (int i = 0; i < arr.length; i++) {
6    System.out.println("Index " + i + ": " + arr[i]);
7}
8
9// Method 2: Enhanced for loop (cleaner for read-only)
10for (int value : arr) {
11    System.out.println(value);
12}
13
14// Method 3: While loop
15int i = 0;
16while (i < arr.length) {
17    System.out.println(arr[i++]);
18}
19
20// Method 4: Streams (Java 8+)
21Arrays.stream(arr).forEach(System.out::println);

Common array calculations

java
1// Common operations
2int[] numbers = {5, 2, 8, 1, 9, 3};
3
4// Find sum
5int sum = 0;
6for (int n : numbers) {
7    sum += n;
8}
9System.out.println("Sum: " + sum);  // 28
10
11// Find max
12int max = numbers[0];
13for (int n : numbers) {
14    if (n > max) max = n;
15}
16System.out.println("Max: " + max);  // 9
17
18// Find min
19int min = numbers[0];
20for (int n : numbers) {
21    if (n < min) min = n;
22}
23System.out.println("Min: " + min);  // 1
24
25// Find average
26double avg = (double) sum / numbers.length;
27System.out.println("Avg: " + avg);  // 4.666...

Different ways to copy arrays

java
1// Array copying
2int[] original = {1, 2, 3, 4, 5};
3
4// Method 1: Manual copy
5int[] copy1 = new int[original.length];
6for (int i = 0; i < original.length; i++) {
7    copy1[i] = original[i];
8}
9
10// Method 2: System.arraycopy()
11int[] copy2 = new int[original.length];
12System.arraycopy(original, 0, copy2, 0, original.length);
13
14// Method 3: Arrays.copyOf()
15int[] copy3 = Arrays.copyOf(original, original.length);
16
17// Method 4: clone()
18int[] copy4 = original.clone();
19
20// CAUTION: Assignment doesn't copy!
21int[] notACopy = original;  // Both point to SAME array!
22notACopy[0] = 100;          // original[0] is also 100 now!

Use Cases

  • Storing fixed collections of data
  • Implementing other data structures (stack, queue)
  • Lookup tables and caching
  • Buffer for I/O operations
  • Mathematical computations
  • Algorithm implementations

Common Mistakes to Avoid

  • ArrayIndexOutOfBoundsException from bad index
  • Confusing length property with length() method
  • Assignment instead of copy (both reference same array)
  • Not initializing elements before use
  • Off-by-one errors in loops
  • Using == to compare array contents (use Arrays.equals())