0
Explore
0

Arrays in Java (1D & 2D) – A Complete Guide for Beginners

Updated on July 30, 2025

In Java, we often need to store multiple values of the same type (like multiple numbers or names). Instead of creating many variables, we use arrays, a data structure that lets us store and access multiple values using one variable name.

Think of an array like a row of lockers. Each locker has a number (index) and can hold a value (data).

What is an Array in Java?

An array in Java is a container object that holds a fixed number of values of the same data type. Think of it like a row of mailboxes or a row of chairs in a theater, each slot holds something, and you can access it by its number (index).

Let’s now go deeper into the official explanation:

“An array is a collection of similar data types stored in contiguous memory locations.”

Let’s break this statement into simpler parts:

  1. ✅ Collection of similar data types:
    • This means all elements in the array must be of the same type.
    • For example: You can have an array of int (integers), but not a mix of int and String. Example: int[] numbers = {10, 20, 30}; ✅ int[] mixed = {10, “Hello”, 20}; ❌ (invalid — mixed data types)
  2. ✅ Stored in contiguous memory locations:
    • The array elements are stored one after the other in memory.
    • This improves access speed because the program can calculate the exact memory address of each element directly.

Visual Example of Array:

Let’s say you create this array:

int[] arr = {5, 10, 15, 20};

Memory layout (simplified):

IndexValue
05
110
215
320

Each value is stored in sequence, so accessing arr[2] directly gets us 15.

Java Supports Arrays of:

1. Primitive types:

  • int, float, double, char, byte, short, long, boolean
Example:

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

2. Objects:

  • String, Student, Book, etc.
Example:

String[] names = {"Ram", "Shyam", "Mohan"}; 

Student[] students = new Student[3]; // assuming Student is a class you created

Key Features of Arrays in Java

Let’s explore each of the points mentioned:

1. 🔒 Fixed Size (declared during creation):

  • Once you create an array, its size cannot be changed.
  • Example: int[] arr = new int[5]; // This array can store only 5 elements
  • If you need dynamic size, you can use ArrayList (not covered here).

2. 📚 Same Data Type:

  • All elements must be of the same type.
  • This enforces consistency and avoids unexpected errors.
  • The type is decided at the time of array declaration.

3. 🔢 Index Starts from 0:

  • Java arrays use zero-based indexing.
  • This means the first element is at index 0, the second at index 1, and so on.

Example:

String[] colors = {"Red", "Green", "Blue"}; 
colors[0] → "Red" 
colors[2] → "Blue" 
Accessing colors[3] → ❌ Error: ArrayIndexOutOfBoundsException

4. 🧠 Stored in Heap Memory:

  • All arrays in Java are objects.
  • Objects in Java are always stored in heap memory (not stack memory).
  • Even if you declare an array inside a method, its contents live in the heap.

Why is this important?

  • Memory in the heap is shared and can be accessed by multiple methods and threads.
  • Also, this is why arrays can be large in size — the heap is generally much bigger than the stack.

How Do Arrays Work in Java Behind the Scenes?

When you create an array like this:

int[] arr = new int[4];

Java performs the following steps:

  • Allocates memory for 4 integers in the heap.
  • Initializes each element to the default value (0 for int, false for boolean, null for objects).
  • Stores a reference (address) to the array in the variable arr.

Example: Memory visualization

int[] arr = new int[3];
System.out.println(arr[0]); // Output: 0

Memory:

IndexValue
00
10
20

Tip: All elements of an array are automatically initialized based on the data type:

  • int → 0
  • boolean → false
  • double → 0.0
  • char → ‘\u0000’ (null character)
  • object reference → null

When Should You Use Arrays?

  • When you know the number of elements in advance
  • When you need fast random access (arr[i] is O(1))
  • When working with fixed-size collections (like days of week, months)

When Not to Use Arrays?

  • When the size needs to grow/shrink dynamically → use ArrayList
  • When you need complex key-value mappings → use HashMap

One-Dimensional Array (1D Array)

Declaration and Initialization:

int[] marks;          // Declaration
marks = new int[5];   // Memory allocation for 5 integers

Or do it in one line:

int[] marks = new int[5];

Or with values:

int[] marks = {90, 85, 75, 88, 92};

Accessing and Modifying Values:

System.out.println(marks[0]);  // Output: 90
marks[2] = 95;                 // Change 3rd element to 95

Traversing a 1D Array:

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

Example: Sum of Array Elements

public class ArraySum {
    public static void main(String[] args) {
        int[] nums = {10, 20, 30, 40, 50};
        int sum = 0;

        for(int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }

        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 150

Common Mistake in 1D Arrays

int[] arr = new int[3];
arr[3] = 100; // ❌ Error: Index 3 is out of bounds (valid: 0 to 2)

Two-Dimensional Array (2D Array)

A 2D array is like a table or matrix — rows and columns.

Declaration and Initialization:

int[][] matrix = new int[3][2];  // 3 rows, 2 columns

Or initialize directly:

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

Accessing 2D Array Elements:

System.out.println(matrix[0][1]); // Output: 2 (1st row, 2nd column)

Traversing 2D Array using Nested Loops:

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();
}

Example: Matrix Addition

public class MatrixAddition {
    public static void main(String[] args) {
        int[][] A = {
            {1, 2},
            {3, 4}
        };
        int[][] B = {
            {5, 6},
            {7, 8}
        };

        int[][] result = new int[2][2];

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

        System.out.println("Sum Matrix:");
        for(int[] row : result) {
            for(int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}

Output:

Sum Matrix:
6 8
10 12

Key Properties of Arrays in Java

PropertyDescription
array.lengthGives the size of the array
Zero-based indexingIndex starts from 0
Fixed sizeOnce declared, the size can’t be changed
Stored in heap memoryObjects including arrays are in heap
Supports for-eachEasy looping through elements

For-Each Loop (Enhanced for Loop)

Simplifies traversing arrays.

int[] nums = {10, 20, 30};
for(int n : nums) {
    System.out.println(n);
}

Array of Objects (Reference Data Types)

String[] names = {"Alice", "Bob", "Charlie"};

for(String name : names) {
    System.out.println("Name: " + name);
}

You can also create arrays of custom objects like:

Student[] students = new Student[3];
students[0] = new Student("Prakash", 90);

Memory Representation of Arrays

1D Array:

Index:   0   1   2   3
Value:  10  20  30  40

2D Array:

      Col0 Col1
Row0    1    2
Row1    3    4
Row2    5    6

Each row of a 2D array is itself a 1D array!

Practice Problems

  1. Store 10 numbers in an array and print the reverse.
  2. Count how many numbers are even in an array.
  3. Find the maximum and minimum elements in a 1D array.
  4. Input a 3×3 matrix and print its diagonal elements.
  5. Transpose a matrix (swap rows and columns).

Quiz Time!

Q1. What is the index of the first element in an array?
Q2. What does array.length return?
Q3. Can we store different data types in a single array?
Q4. What will happen if you try to access an index that doesn’t exist?

Real-Life Applications of Arrays

  • Store marks of students
  • Represent a matrix or grid (like a game board)
  • Hold a list of tasks or items
  • Track sensor values or data streams

Summary

Concept1D Array2D Array
StructureLinearMatrix (Rows and Columns)
Syntaxint[] arr = new int[5];int[][] mat = new int[3][2];
Accessarr[i]mat[i][j]
TraversalSingle for loopNested for loops

Final Thoughts

Arrays are the foundation of many data structures and algorithms. Mastering 1D and 2D arrays will help you work with more advanced concepts like:

What to Learn Next?

  • ArrayList (dynamic arrays)
  • Multidimensional Arrays (3D)
  • Sorting algorithms using arrays (Bubble Sort, Selection Sort)
  • String as character arrays