Arrays in Java – Single & Multi-dimensional Arrays, Array Operations


Table of Contents

  1. What Are Arrays?
  2. Advantages of Using Arrays
  3. Declaring and Initializing Arrays
  4. Accessing and Modifying Elements
  5. Iterating Through Arrays
  6. Multi-dimensional Arrays
  7. Common Array Operations
  8. Arrays vs ArrayList
  9. Real-world Examples
  10. Summary and What’s Next

1. What Are Arrays?

In Java, an array is a data structure that allows you to store multiple values of the same data type in a single variable. Arrays are fixed in size and indexed, meaning that each element can be accessed using its position (or index), starting from 0.

Arrays are one of the most basic and essential constructs in programming, used in countless applications from mathematical operations to organizing large datasets.


2. Advantages of Using Arrays

  • Efficiency: Arrays allow you to group related data together, making storage and manipulation more efficient.
  • Indexed Access: You can directly access any element in constant time using its index.
  • Ease of Iteration: Arrays can easily be looped through, especially with constructs like the enhanced for-loop.
  • Memory Management: Java arrays are stored in contiguous memory locations, improving data locality and access speed.

3. Declaring and Initializing Arrays

Declaration

int[] numbers;
String[] names;

Initialization with size

int[] numbers = new int[5];  // Array of 5 integers

Initialization with values

int[] numbers = {10, 20, 30, 40, 50};

Assigning elements manually

numbers[0] = 10;
numbers[1] = 20;

Arrays in Java are objects, so when declared, memory is allocated on the heap.


4. Accessing and Modifying Elements

Each element in an array is accessed using its index:

System.out.println(numbers[2]); // prints 30
numbers[2] = 35; // modifies the third element

If you try to access an index outside the array bounds, Java throws an ArrayIndexOutOfBoundsException.


5. Iterating Through Arrays

Using a traditional for loop:

for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

Using an enhanced for-each loop:

for (int number : numbers) {
System.out.println(number);
}

The enhanced loop is simpler but doesn’t give access to indices. Use it when you just need values.


6. Multi-dimensional Arrays

Java also supports arrays of arrays, often used for matrices and tables.

Declaration and Initialization

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Accessing Elements

System.out.println(matrix[1][2]); // prints 6

Iterating

for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

Multi-dimensional arrays are arrays of arrays in Java, not flat 2D structures like in some other languages.


7. Common Array Operations

Finding Maximum or Minimum

int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}

Reversing an Array

for (int i = 0; i < numbers.length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[numbers.length - 1 - i];
numbers[numbers.length - 1 - i] = temp;
}

Copying Arrays

int[] copy = Arrays.copyOf(numbers, numbers.length);

Java provides utility classes like Arrays to assist with common array operations like sorting, searching, and copying.


8. Arrays vs ArrayList

FeatureArrayArrayList
SizeFixedDynamic
Type SafetyPrimitive & ObjectsObjects only
PerformanceSlightly fasterMore flexible
MethodsNo built-inRich API

When working with dynamic or frequently resized collections, consider using ArrayList from the java.util package instead of arrays.


9. Real-world Examples

Example 1: Storing student scores

int[] scores = new int[5];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter score " + (i + 1) + ": ");
scores[i] = sc.nextInt();
}

Example 2: Basic Matrix Multiplication (2×2)

int[][] A = {{1, 2}, {3, 4}};
int[][] B = {{5, 6}, {7, 8}};
int[][] C = new int[2][2];

for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}

This example demonstrates the power of multi-dimensional arrays in mathematical computation.


10. Summary and What’s Next

In this module, we covered:

  • The basics of arrays in Java, including declaration, initialization, and iteration
  • Working with both single and multi-dimensional arrays
  • Performing key operations like searching, reversing, and copying
  • Understanding differences between arrays and ArrayList

Arrays form the foundation of many data structures and are critical to efficient memory and data management in Java.