View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Array in Java: Types, Operations, Pros & Cons

By Rohan Vats

Updated on Jun 04, 2025 | 9 min read | 16.98K+ views

Share:

Did you know? Java remains one of the top programming languages in 2025. It ranked #2 in Pluralsight’s annual report and held the #3 spot in both the TIOBE Index (November 2024) and RedMonk Q3 2024 rankings, just behind Python and C++ or JavaScript. Its consistent performance shows Java’s lasting importance in today’s tech ecosystem. This study showcases the importance of Java in the tech industry. 

Arrays in Java are a fundamental data structure that allows you to store multiple elements of the same type in a single container. They offer a simple yet powerful way to manage data efficiently, making them a core concept in Java programming. Java provides various types to suit different needs, from single to multi-dimensional arrays.

Understanding arrays is essential for effectively performing key operations like searching, sorting, and iteration.
This blog explores arrays in Java, the different types of arrays in Java, Java array operations, and their advantages and limitations.

Looking to strengthen your core programming concepts? Building expertise in fundamentals like Arrays in Java is key to writing efficient, high-performance code. upGrad’s Online Software Development Courses equip you with in-demand skills, from data structures to full-stack development, helping you stay ahead in today’s AI-powered tech ecosystem.

What is an Array in Java? Core Concepts

An array refers to a data structure that contains homogeneous elements. This means that all the elements in the array are of the same data type in a single, fixed-size container. Instead of creating separate variables for each item, you group them together under one name and access them using an index.

  • You work with a single structured collection rather than scattered variables.
  • The array holds values in contiguous memory locations, enabling fast access.
  • Each element is identified by an index starting from 0, making retrieval and updates simple.
  • Arrays are ideal when you know the number of elements and need efficient access or iteration.
  • They are handy in storing datasets, processing lists, or handling repetitive operations.

If you want to deepen your understanding of Java and other core programming concepts like arrays, the following upGrad courses can help boost your skills and prepare you for real-world development challenges.

Syntax of an array in Java

int[] numbers;         // Recommended syntax
String[] names;        // Array of Strings
double[] prices;       // Array of doubles

Steps for Array Setup in Java

When working with arrays in Java, you follow three basic steps to create and prepare the array before using it. These steps are part of the language syntax, not data structure operations.

1. Declaring an Array in Java

When you declare an array, you tell the compiler what kind of data you want to store and that you plan to store multiple values of that data type. You are not yet allocating memory; you are just defining the structure.

Think of this step as saying, "I want a container to hold several integers, strings, or doubles. But I’ll decide the actual size or values later."

Java Array Example:

public class Main {
    public static void main(String[] args) {
        int[] marks;  // Declaration
        System.out.println("Array declared successfully.");
    }
}

Code Explanation: In this code, the line int[] marks is an example of an array declaration in Java. When you declare an array, you're informing the compiler about the type of data the array will hold

Output:

Array declared successfully.

Also Read: Difference Between Compiler and Interpreter

2. Initializing an Array

Initialization means allocating memory and optionally setting initial values. You say, “Okay, Java, I need space for 5 integers,” or “Here are the values I want from the start.”

Java Array Example:

public class Main {
    public static void main(String[] args) {
        int[] marks = new int[3];  // Initializes with default values 0, 0, 0
        System.out.println("Marks: " + marks[0] + ", " + marks[1] + ", " + marks[2]);
    }
}

Code Explanation: In this code, an integer array named marks is both declared and initialized in a single step using the statement int[] marks = new int[3];. This line creates an array capable of holding three integers. Since the size is specified as 3, memory is allocated for three elements, and Java automatically fills them with the default value for integers, which is 0. Therefore, the array now contains the values [0, 0, 0].

Output:

Marks: 0, 0, 0

Also Read: What is Memory Allocation in Java? Learn Key Memory Areas

3. Assigning Values to an Array

Assigning means placing values at specific positions in the array using index numbers. Indexing in Java arrays starts from 0, so the first position is index 0, the second is 1, and so on

Java Array Example:

public class Main {
    public static void main(String[] args) {
        int[] marks = new int[3];      // Initialized with default 0s
        marks[0] = 85;                 // Assign value to index 0
        marks[1] = 90;                 // Assign value to index 1
        marks[2] = 75;                 // Assign value to index 2

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

Code Explanation: In this program, an integer array named marks is declared and initialized using int[] marks = new int[3];, which creates space in memory to hold three integer values, each initially set to the default value 0. 

After initialization, the array elements are explicitly assigned new values using index-based access. Specifically, marks[0] = 85;, marks[1] = 90;, and marks[2] = 75; assign scores to each student. These assignments overwrite the default values and store the actual data in the array. 

Output:

Student 1: 85
Student 2: 90
Student 3: 75

Looking to strengthen your Java skills with a solid understanding of object-oriented programming? upGrad’s free Java Object-oriented Programming course helps you grasp key concepts like classes, objects, inheritance, polymorphism, encapsulation, and abstraction through hands-on examples.

Also Read: Creating a Dynamic Array in Java

Array Properties in Java

Understanding the key properties of arrays helps you use them effectively:

  • Fixed Size: Once created, the size of an array cannot be changed.
  • Indexed Elements: Elements are stored in contiguous memory locations and accessed via zero-based indices.
  • Homogeneous Data: All elements must be of the same data type.
  • Default Values: Elements have default values if not explicitly assigned (0 for numeric types, false for boolean, null for objects).
  • Length Property: Arrays have a built-in length property that stores their size (array.length).
  • Reference Type: Arrays are objects in Java, so the variable holds a reference to the array.

Also Read: Mastering Operators in Java: The Ultimate Guide to Efficient and Effective Programming

Now that we understand what an array is and how it works at a fundamental level, let's explore the core operations that can be performed on arrays in Java to manipulate and access data efficiently.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Core Java Array Operations

Arrays in Java are powerful, but they become handy when you understand the operations you can perform on them. Common Java array operations such as traversal, insertion, deletion, searching, and sorting allow you to manipulate and analyze data efficiently. Gaining a strong grasp of these operations is essential for tasks ranging from basic data storage to complex algorithm development.

To help you quickly grasp how arrays work in Java, here’s a simplified table that outlines key operations, what they do, what they need, and an example for each:

Operation

Description

Input / Output

Example

Traversal Accesses each element of the array

Input: Array

Output: Elements one by one

Loop through int[] arr = {1, 2, 3} and print each value
Insertion Adds an element at a specific index

Input: Array, index, value

Output: New array with inserted value

Insert 25 at index 2 in {10, 20, 30} → {10, 20, 25, 30}
Deletion Removes an element from a specific index

Input: Array, index

Output: New array without that element

Delete element at index 1 in {5, 15, 25} → {5, 25}
Searching Finds the index of a value in the array

Input: Array, value

Output: Index or -1

Search 9 in {4, 9, 7} → returns 1

Now that you’ve seen a quick overview of the core array operations, let’s break each down with detailed explanations, real-world examples, and Java code to help you understand how and when to use them effectively.

1. Traversal

What it does: Goes through each element of the array.

When to use: Useful for reading values or applying logic to each element.

public class Main {
    public static void main(String[] args) {
        int[] scores = {80, 90, 70, 60};
        for (int i = 0; i < scores.length; i++) {
            System.out.println("Score " + (i + 1) + ": " + scores[i]);
        }
    }
}

Code Explanation: This code creates an array called scores with four numbers. It then uses a loop to go through each number in the array one by one and prints it out with its position. The loop runs from the first score to the last, showing all the values in order.

Output:

Score 1: 80
Score 2: 90
Score 3: 70
Score 4: 60

Also Read: Looping Statements in Java: Types, Syntax, Examples & Best Practices

2. Insertion

What it does: It inserts a new element at a specified index by creating space by shifting existing elements one position to the right, allowing the new value to be placed correctly in the array.

When to use: When adding elements mid-array in a static structure.

public class Main {
    public static void main(String[] args) {
        int[] original = {10, 20, 30, 40};
        int insertPos = 2, newValue = 25;
        int[] updated = new int[original.length + 1];

        for (int i = 0, j = 0; i < updated.length; i++) {
            if (i == insertPos) {
                updated[i] = newValue;
            } else {
                updated[i] = original[j++];
            }
        }

        for (int val : updated) {
            System.out.print(val + " ");
        }
    }
}

Code Explanation: This code inserts a new value into an existing array at a specific position. Since arrays have a fixed size, it creates a new, bigger array and copies the old elements into it. When it reaches the position where the new value should go, it inserts that value and then continues copying the rest of the elements. 

Output:

10 20 25 30 40

3. Deletion

What it does: Removes the element at a specified index by shifting all subsequent elements one position to the left, effectively overwriting the removed element and maintaining the array’s order.

When to use: Useful in static arrays where removal must be simulated.

public class Main {
    public static void main(String[] args) {
        int[] original = {10, 20, 30, 40, 50};
        int deleteIndex = 2;
        int[] updated = new int[original.length - 1];

        for (int i = 0, j = 0; i < original.length; i++) {
            if (i != deleteIndex) {
                updated[j++] = original[i];
            }
        }

        for (int val : updated) {
            System.out.print(val + " ");
        }
    }
}

Code Explanation: This code removes an element from the original array at a specific position. It creates a new, smaller array and copies all elements except the one at the position to be deleted. Finally, it prints the updated array without the removed element.

Output:

10 20 40 50

Also Read: Dynamic Arrays in C: Efficient Memory Allocation Explained

4. Searching

What it does: Finds the position of a specific value.

When to use: Anytime you need to know if an element exists or where it is.

public class Main {
    public static void main(String[] args) {
        int[] arr = {3, 8, 5, 2, 7};
        int searchVal = 5;
        int foundAt = -1;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == searchVal) {
                foundAt = i;
                break;
            }
        }

        System.out.println("Element found at index: " + foundAt);
    }
}

Code Explanation: This code looks through the array to find the position of a specific value (5). It checks each element individually, and if it finds the value, it saves the index and stops searching. Finally, it prints the index where the value was found, or -1 if it’s not in the array.

Output:

Element found at index: 2

5. Sorting

What it does: Reorders elements in ascending or descending order.

When to use: Essential for efficient searching and comparisons.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = {5, 2, 9, 1, 6};
        Arrays.sort(nums);

        for (int n : nums) {
            System.out.print(n + " ");
        }
    }
}

Code Explanation: This code sorts an array of numbers in ascending order using the built-in Arrays.sort() method, then prints each number one by one after sorting.

Output:

1 2 5 6 9

6. Updating

What it does: Modifies an existing value at a given index.

When to use: Useful for replacing incorrect or old data.

public class Main {
    public static void main(String[] args) {
        int[] prices = {100, 200, 300};
        prices[1] = 250;  // Update index 1 from 200 to 250

        for (int p : prices) {
            System.out.print(p + " ");
        }
    }
}

Code Explanation: This code updates the second element of the prices array from 200 to 250, then prints all the array elements to show the updated values.

Output:

100 250 300

You can get a better hang of Java with upGrad’s free Core Java Basics course. It covers variables, data types, loops, and OOP principles to build strong coding skills. Perfect for aspiring developers, students, and professionals transitioning to Java.

Also Read: Top 10 Free Java Courses with Certificates for In-Demand Java Jobs

Now that you're familiar with how array operations work, let's explore the different types of arrays in Java and understand when to use each of them.

Different Types of Arrays in Java

Java supports different types of arrays to handle various data structures and programming needs. Understanding these helps you organize and manage data more effectively.

1. One-Dimensional Array in Java

A 1D Array in Java is a linear structure that lets you store multiple values of the same data type. You can use it to hold anything from integers, strings, and booleans to even objects of custom classes, depending on your needs. Declaring and initializing a single-dimensional array is similar to working with regular variables. Still, instead of assigning just one value, you define a fixed size or provide multiple values separated by commas within curly braces.

Syntax for Declaration of a One-Dimensional Array in Java

Below is the syntax to declare a one-dimensional array in Java

data_type array_name[array_size];

where,

  • data_type: is the type of data of each array block.
  • array_name: is the array's name, using which we can refer to it.
  • array_size: is the number of blocks of memory the array will have.

Example Code:

public class Example {

 public static void main(String args[]) {
  int arr[] = { 1, 5, 10, 15, 20 }; // initializing array
  for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i] + " "); // printing array elements
  }
}
}

Note:

  • Since we chose the int data type, we can only add integer values to the array. So, the variable type depends on the array's data type.
  • The size of the array depends on how many values we are providing at the time of initialization.
  • The size of one-dimensional arrays cannot be changed once created.

Output:

1  5  10  15  20

Also Read: String Functions In Java | Java String [With Examples]

2. Multidimensional Array in Java

A multidimensional array in Java is an array of arrays. You can think of it like a grid or a table: a single structure that holds multiple rows, and each row holds multiple columns.

It can be visualized like this:

int[][] matrix = {
    {10, 20, 30},
    {40, 50, 60},
    {70, 80, 90}
};

This is a 3x3 array:

  • 3 rows
  • 3 columns per row
  • Total elements = 3 × 3 = 9

You access elements using two indices:

  • matrix[0][0]: First row, first column → 10
  • matrix[2][1]: Third row, second column → 80

Example Code:  Searching for an Element in a 2D Array

Here’s how you can search for a specific element in a 2D array:

public class Main {
    public static void main(String[] args) {
        int[][] matrix = {
            {10, 20, 30},
            {40, 50, 60},
            {70, 80, 90}
        };

        int target = 50;
        boolean found = false;

        for (int i = 0; i < matrix.length; i++) {            // Loop through rows
            for (int j = 0; j < matrix[i].length; j++) {      // Loop through columns
                if (matrix[i][j] == target) {
                    System.out.println("Element " + target + " found at row " + i + ", column " + j);
                    found = true;
                    break;
                }
            }
            if (found) break;
        }

        if (!found) {
            System.out.println("Element not found in the array.");
        }
    }
}

Code Explanation: 

  • The matrix is a 2D array containing integers.
  • The target is the value you want to search for.
  • Two nested for loops are used:
  • The outer loop goes through each row.
  • The inner loop goes through each column in that row.
  • If the target value is found, its position (row and column index) is printed.
  • A message is shown if it’s not found after checking all elements.

Output:

Element 50 found at row 1, column 1

Output Explanation: The number 50 is located at row index 1 and column index 1 of the array, corresponding to the second row and second column in the 2D structure.

3. Three-Dimensional Array in Java

A three-dimensional array in Java is essentially an array of two-dimensional arrays. You can think of it as a cube or a group of tables, where each “layer” is a 2D array, and multiple such layers are stacked together in a single 3D structure.

It can be visualized like this:

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

This is a 2x2x2 array:

  • 2 layers (outer array)
  • Each layer has 2 rows
  • Each row has 2 columns
  • Total elements = 2 × 2 × 2 = 8

You access elements using three indices:

  • cube[0][0][0]: First layer, first row, first column → 1
  • cube[1][1][1]: Second layer, second row, second column → 8

Example Code: Searching for an Element in a 3D Array

Here’s how you can search for a specific element in a 3D array:

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

        int target = 7;
        boolean found = false;

        for (int i = 0; i < cube.length; i++) {               // Loop through layers
            for (int j = 0; j < cube[i].length; j++) {        // Loop through rows
                for (int k = 0; k < cube[i][j].length; k++) { // Loop through columns
                    if (cube[i][j][k] == target) {
                        System.out.println("Element " + target + " found at layer " + i + ", row " + j + ", column " + k);
                        found = true;
                        break;
                    }
                }
                if (found) break;
            }
            if (found) break;
        }

        if (!found) {
            System.out.println("Element not found in the array.");
        }
    }
}

Code Explanation:

  • cube is a 3D array made up of two 2D arrays.
  • The target is the value you want to search for.
  • Three nested for loops are used:
    • The outer loop goes through each layer.
    • The middle loop accesses rows within a layer.
    • The inner loop accesses columns within a row.
  • If the target is found, its position (layer, row, column) is printed.
  • If not found, it shows a message after checking all elements.

Output:

Element 7 found at layer 1, row 1, column 0

Output Explanation:

The number 7 is located at layer index 1, row index 1, and column index 0, which means it appears in the second layer, second row, and first column of the 3D structure.

Also Read: How to Code, Compile, and Run Java Projects: A Beginner’s Guide

Commonly Used Array Methods in Java

While Java arrays are powerful, they don’t offer many built-in methods. Most array-related functionality is provided through the java.util.Arrays utility class, which includes methods for sorting, copying, searching, and comparing arrays.

Understanding these methods not only saves time but also improves the readability and efficiency of your code.

1. Arrays.toString(array)

Purpose: Converts a one-dimensional array into a human-readable String.

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4};
        System.out.println(Arrays.toString(numbers));
    }
}

Output:

[1, 2, 3, 4]

Explanation:
Without this method, printing an array directly (System.out.println(numbers)) would print its memory address. Arrays.toString() provides a readable representation.

2. Arrays.sort(array)

Purpose: Sorts elements in ascending order (natural order for numbers and strings).

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] nums = {5, 2, 8, 1};
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));
    }
}

Output:

[1, 2, 5, 8]

Explanation:
This method modifies the original array and sorts it in-place.

3. Arrays.equals(array1, array2)

Purpose: Compares two arrays for content equality.

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println(Arrays.equals(a, b));
    }
}

Output:

true

Explanation:
Returns true if both arrays are of equal length and contain the same elements in the same order.

4. Arrays.fill(array, value)

Purpose: Fills all elements in an array with the same value.

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] marks = new int[5];
        Arrays.fill(marks, 10);
        System.out.println(Arrays.toString(marks));
    }
}

Output:

[10, 10, 10, 10, 10]

Explanation: Helpful in initializing arrays with default values.

5. Arrays.copyOf(array, newLength)

Purpose: Copies an array and optionally changes its size.

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] original = {1, 2, 3};
        int[] copied = Arrays.copyOf(original, 5);
        System.out.println(Arrays.toString(copied));
    }
}

Output:

[1, 2, 3, 0, 0]

Explanation: Extra elements are filled with default values. This is helpful when resizing static arrays.

6. Arrays.copyOfRange(array, from, to)

Purpose: Create a copy of a specific range (the exclusive end index).

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] data = {10, 20, 30, 40, 50};
        int[] subset = Arrays.copyOfRange(data, 1, 4);
        System.out.println(Arrays.toString(subset));
    }
}

Output:

[20, 30, 40]

Explanation: Great for extracting a slice from an array.

7. Arrays.binarySearch(array, key)

Purpose: Finds the index of a value using binary search (only works on sorted arrays).

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[] scores = {10, 20, 30, 40, 50};
        int index = Arrays.binarySearch(scores, 30);
        System.out.println(index);
    }
}

Output:

2

Explanation: Returns the index of the searched value or a negative value if not found.

Also Read: What is Binary Search Algorithm? Its Working and Complexities Explained

8. Arrays.deepToString(array)

Purpose: Converts nested (multi-dimensional) arrays into a readable string.

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2}, {3, 4}};
        System.out.println(Arrays.deepToString(matrix));
    }
}

Output:

[[1, 2], [3, 4]]

Explanation: Use this for multi-dimensional arrays; toString() won't work correctly on nested arrays.

9. Arrays.deepEquals(array1, array2)

Purpose: Compares nested arrays for deep equality.

Code Example:

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        int[][] a = {{1, 2}, {3, 4}};
        int[][] b = {{1, 2}, {3, 4}};
        System.out.println(Arrays.deepEquals(a, b));
    }
}

Output:

true

Explanation: Unlike Arrays.equals(), which fails on nested arrays, this correctly compares each inner array.

10. Arrays.asList(array)

Purpose: Converts an array to a fixed-size List (only works with object arrays, like String[]).

Code Example:

import java.util.*;

public class Example {
    public static void main(String[] args) {
        String[] languages = {"Java", "Python", "C++"};
        List<String> list = Arrays.asList(languages);
        System.out.println(list);
    }
}

Output:

[Java, Python, C++]

Explanation: This function allows array elements to be used like a List. Remember that the size is fixed, and primitive arrays (int[]) will not work as expected.

If you want to build a higher-level understanding of Javascript, upGrad’s Advanced Javascript for All course is what you need. Learn about prototypes, scopes, classes, modules, async programming, and more to enhance your web development skills and become a proficient JS developer.

Also Read: Object Class in Java: Methods, Usage, and Examples Explained

Passing and Returning Arrays in Java

In Java, arrays are objects. You can pass arrays to methods just like you pass variables, and return arrays from methods. This allows methods to work with large data sets and return results efficiently.

But there’s a key difference between passing a primitive variable (like int or double) and passing an array:

Feature

Primitive Variable (int, double, etc.)

Array (int[], String[], etc.)

What is passed A copy of the value A reference (memory address)
Can the method be modified? No changes don’t affect the original. Yes — changes affect the original array.

Here's a complete breakdown of the difference between passing a primitive variable and a Java array.

1. Passing a Primitive Variable (e.g., int)

public class PrimitiveExample {
    public static void changeValue(int num) {
        num = 100;  // Change inside the method
    }

    public static void main(String[] args) {
        int x = 50;
        changeValue(x);
        System.out.println("Value after method call: " + x);
    }
}

Output:

Value after method call: 50

Explanation:

  • The method receives a copy of x, not the original.
  • Changing num doesn’t affect the actual value of x.

 2. Passing an Array

public class ArrayExample {
    public static void changeArray(int[] arr) {
        arr[0] = 100;  // Change inside the method
    }

    public static void main(String[] args) {
        int[] numbers = {50, 60, 70};
        changeArray(numbers);
        System.out.println("First element after method call: " + numbers[0]);
    }
}

Output:

First element after method call: 100

Explanation:

  • The method receives a reference to the array.
  • Modifying arr[0] changes the actual numbers[0], because they point to the same memory.

3. Returning Arrays from Methods

You can return arrays from methods to send a set of values back to the caller.

public class ReturnExample {
    public static int[] generateArray() {
        int[] arr = {5, 10, 15};
        return arr;
    }

    public static void main(String[] args) {
        int[] result = generateArray();
        System.out.println(java.util.Arrays.toString(result)); 
    }
}

Explanation:

  • The method generateArray() creates and returns a new array.
  • The calling method stores the returned array and prints it using Arrays.toString().

Output:

[5, 10, 15]

Also Read: Pass By Value and Call By Reference in Java

Array Cloning and Copying in Java

When working with arrays in Java, cloning is a common way to create a copy of an array. However, it’s important to understand that cloning can behave differently depending on the type of data stored inside the array. This leads us to two main types of copies:

  • Shallow Copy: Copies the array structure and references, but not the objects that those references point to. So changes to objects inside the copied array affect the original array.
  • Deep Copy: Creates a completely independent copy of the array and all objects within it, so changes do not affect the original array.

Java's built-in .clone() method performs a shallow copy. For deep copying, you must manually copy each object inside the array.

Copy Type

What is Copied?

Effect on Original Array When Copied Array Changes

How to Achieve in Java

Shallow Copies the array and references to objects (for object arrays) Modifying objects inside a copied array affects the original Use .clone() method
Deep Copies the array and creates new copies of all objects inside it Modifying objects inside the copied array does not affect the original Manually clone/copy each object in the array

Now, let's dive into detailed examples to illustrate shallow and deep copy cloning in Java.

1. Shallow Copy Cloning Arrays using .clone()

Java provides the .clone() method built into every array. It creates a new array, copying primitive values or references of objects, but not the objects themselves.

Works Best For:

  • Primitive type arrays like int[], char[]
  • Quick duplication where deep copy isn't needed

 Example:

public class CloneExample {
    public static void main(String[] args) {
        int[] original = {10, 20, 30};
        int[] cloned = original.clone();

        original[0] = 99;

        System.out.println("Original: " + java.util.Arrays.toString(original));
        System.out.println("Cloned:   " + java.util.Arrays.toString(cloned));
    }
}

Output:

Original: [99, 20, 30]
Cloned:   [10, 20, 30]

Explanation:

  • The clone() method created a new array.
  • The change to original[0] did not affect cloned[0].
  • For primitive data types, it behaves like a true copy.
  • For object arrays, only references are copied, not the objects themselves.

2. Deep Copy Cloning Example

When dealing with arrays of objects, simply cloning the array creates a shallow copy—the array itself is duplicated, but the objects inside are still shared references. This means changes to the objects through the cloned array will affect the original objects, which can cause unintended side effects, bugs, or data corruption.

You need a deep copy to completely isolate the cloned array from the original. A deep copy duplicates the array and all the individual objects inside it, so that modifications to the clone do not impact the original.

Why Prefer Deep Copy?

  • Avoid unintended side effects: Modifying the clone won’t affect the original objects, preserving data integrity.
  • Safe data manipulation: Useful in multi-threaded environments or complex applications where data must be immutable or protected.
  • Independent lifecycles: Changes, deletions, or additions in the cloned array do not impact the original data.
  • Debugging and maintenance: Easier to track bugs and reason about code when objects are not shared unexpectedly.

How Deep Copy Works

You first clone the array itself (shallow copy) and then clone each object individually inside the array. This requires the object class (like Person) to implement the Cloneable interface and correctly override the clone() method.

class Person implements Cloneable {
    String name;

    Person(String name) {
        this.name = name;
    }

    // Override clone method to enable cloning of Person objects
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public String toString() {
        return name;
    }
}

public class DeepCloneExample {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person[] original = { new Person("Alice"), new Person("Bob") };

        // Step 1: Clone the array itself (shallow copy)
        Person[] deepCloned = original.clone();

        // Step 2: Clone each object in the array for deep copy
        for (int i = 0; i < original.length; i++) {
            deepCloned[i] = (Person) original[i].clone();
        }

        // Modify the cloned array's first person's name
        deepCloned[0].name = "Charlie";

        System.out.println("Original: " + java.util.Arrays.toString(original));
        System.out.println("Deep Cloned: " + java.util.Arrays.toString(deepCloned));
    }
}

Output:

Original: [Alice, Bob]
Deep Cloned: [Charlie, Bob]

Detailed Explanation:

  • The array is duplicated by .clone(), so deepCloned points to a new array object.
  • Each Person object inside the array is cloned individually by invoking clone(). This creates new Person instances with the same state as the originals.
  • When we modify the cloned array’s first person's name (deepCloned[0].name = "Charlie"), the original array remains unaffected because deepCloned[0] points to a different object than original[0].
  • Deep copying achieves this isolation between the original and the clone, preventing accidental changes from propagating back.

Also Read: Multithreading in Java – Learn with Examples

Common Mistakes When Working with Arrays in Java

Arrays are fundamental in Java programming, but working with them can sometimes lead to subtle errors and bugs, especially for beginners. Understanding these common pitfalls will help you write more robust and error-free code. Below are some of the frequent mistakes programmers make when using arrays, along with explanations to help you avoid them.

1. Accessing Out-of-Bounds Indices

Java arrays are zero-indexed, meaning the first element is at index 0 and the last is at array.length - 1. Trying to access an index outside this range, such as array[-1] or array[array.length], will cause an ArrayIndexOutOfBoundsException at runtime. This error stops program execution and must be handled or prevented by validating index values before access.

public class Example {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30};
        System.out.println(arr[3]);  // Invalid index: max valid index is 2
    }
}

Output/Error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Example.main(Example.java:4)

2. Assuming Arrays Can Resize Automatically

Unlike some dynamic data structures (e.g., ArrayList), Java arrays have a fixed length determined at creation time. If you try to add elements beyond the array’s size, you will not get a runtime error immediately. Still, you cannot store more elements without creating a larger variety and copying existing aspects. Forgetting this leads to unexpected behaviors and wasted time debugging.

public class Example {
    public static void main(String[] args) {
        int[] arr = new int[2];
        arr[0] = 5;
        arr[1] = 10;
        // Trying to add a third element (index 2) will cause an error
        arr[2] = 15;  // Array size is only 2
    }
}

Output/Error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Example.main(Example.java:6)

3. Confusing length Property with a Method

In Java, arrays have a built-in property called length (no parentheses) that holds the number of elements. A common mistake is to treat length as a method and use parentheses, like array.length(), which will cause a compile-time error because length is not a method but a final field.

public class Example {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println(arr.length());  // Incorrect usage
    }
}

Output/Error:

Example.java:4: error: cannot find symbol
        System.out.println(arr.length());
                              ^
  symbol:   method length()
  location: variable arr of type int[]

4. Not Initializing Arrays Before Use

Declaring an array variable alone (e.g., int[] arr;) does not create the array object. If you try to access or assign elements without initializing the array (e.g., arr = new int[5];), it will result in a NullPointerException. Always initialize your array before using it to avoid runtime crashes.

public class Example {
    public static void main(String[] args) {
        int[] arr;          // Declared but not initialized
        System.out.println(arr.length);  // Accessing before initialization
    }
}

Output/Error:

Example.java:4: error: variable arr might not have been initialized
        System.out.println(arr.length);

5. Mixing Data Types

Java arrays are strongly typed, which means all elements must be of the declared type. Trying to store mixed types (e.g., integers and strings in the same array) leads to compile-time errors. If you need to store different types, consider using a variety of Object or other suitable data structures, but be mindful of type casting and safety.

public class Example {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        numbers[0] = "Hello";  // Invalid: String assigned to int array
    }
}

Output/Error:

Example.java:5: error: incompatible types: String cannot be converted to int
        numbers[0] = "Hello";
                      ^
1 error

6. Ignoring Default Values of Array Elements

When you initialize an array, its elements are automatically set to default values (0 for numeric types, false for boolean, null for object references). Forgetting this can cause logic errors. For example, assuming elements are null or empty when they actually hold default primitive values. Always explicitly assign values if you need something different.

public class Example {
    public static void main(String[] args) {
        boolean[] flags = new boolean[3];
        for (int i = 0; i < flags.length; i++) {
            System.out.println(flags[i]);  // Prints default 'false'
        }
    }
}

Output:

false
false
false

Also Read: Type Casting in Java: What Is Casting in Java and How to Use It Effectively in 2025

Advantages and Disadvantages of Arrays in Java

Arrays are one of the most fundamental data structures in Java. They offer fast access and efficient storage, but also have certain limitations. The table below outlines the key advantages and disadvantages of using arrays in Java:

Advantages

Disadvantages

Fixed Size: Predictable memory allocation once the array is defined. Fixed Length: Cannot be resized after creation; resizing requires a new array.
Indexed Access: Fast, direct access using indices. No Built-in Insert/Delete: Manual shifting needed for insertion/deletion.
Efficient for Iteration: Easy to loop through using simple constructs. Memory Waste: Unused slots waste memory; too-small arrays require resizing.
Compact Storage: Stored in contiguous memory, improving performance. Limited Built-in Methods: Lacks utility functions found in higher-level structures like ArrayList.
Type-Safe: Enforces a single data type, preventing type mismatches.  

Wrapping Up!

Arrays in Java are a foundational data structure that allows you to store and manage data collections efficiently. By understanding how to declare, initialize, and manipulate arrays, you gain control over how your programs handle everything from simple lists to complex data sets.

You’ve explored the various types of arrays, from single-dimensional to multidimensional, and learned how operations like traversal, insertion, deletion, and sorting are used to manage data effectively. Each operation serves a unique purpose and helps in optimizing your program’s logic, speed, and memory usage.

If you're ready to sharpen your programming skills and create robust and optimized applications, here are some additional upGrad programs that can help you upskill and put your learning into action.

If you're ready to take the next step in your career, connect with upGrad’s career counseling for personalized guidance. You can also visit a nearby upGrad center for hands-on training to enhance your generative AI skills and open up new career opportunities!

References:

  • https://www.pluralsight.com/resources/blog/upskilling/top-programming-languages-2025

Frequently Asked Questions (FAQs)

1. How do I resize an array in Java without losing my existing data?

2. How can I search for multiple occurrences of a value in an array?

3. I want to return an array from a method. What’s the best way to do this?

4. Can I store different data types in a single array?

5. How do I deep copy a multidimensional array in Java?

6. I need to remove an element from an array. How do I do that in Java?

7. What’s the difference between length, length(), and size() in Java arrays?

8. Can I sort an array of custom objects using my own logic?

9. How do I convert an array to a List in Java for more flexibility?

10. I get ArrayIndexOutOfBoundsException. What does that mean and how do I fix it?

11. How do I initialize a large array efficiently in Java?

Rohan Vats

408 articles published

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months