Arrays in Java

What is an Array in Java ?

Before, learning Arrays in Java, first we have to learn about the concept of Arrays in Programming Languages.

It is the fundamental data structure that allows you to store multiple elements of the same data type in a single variable. These elements are stored in contiguous memory locations, making it easy to access and manipulate data efficiently. 

Java arrays are objects that can hold primitive data types like int, char, float, and also non-primitive data types (object references), depending on how the array is declared.

If you’re learning about Java programming, understanding how arrays work is essential for mastering data storage, iteration, and algorithm implementation.

arrays in java programming

What is an Array in Programming Language?

An array is a data structure that stores multiple values of the same data type in a single variable.

In Java, arrays are objects that hold a fixed number of elements, and each element is accessible via its index.

Types of Arrays:

There are two types of array:

  1. Single Dimensional Array
  2. Multidimensional Array
Introduction to Array in Java

Types of Arrays in Java

1. One Dimensional Arrays:

Linear arrays where elements are stored in a single row.

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

2. Multi Dimensional Arrays:

Arrays containing arrays, useful for representing matrices or tables.

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

Operations related to Arrays in Java

Their are 4 main operations that are performed primarily with Arrays.

Here, we have given code example to elaborate them in Java Programming Syntax:

1. Creating Arrays

In Java, arrays are objects that are dynamically allocated. To create an array, you must specify the type of data and the number of elements.

// Declaration and creation
int[] arr = new int[5];

// Declaration, creation, and initialization
int[] arr = {1, 2, 3, 4, 5};

2. Accessing Array Elements

Array elements are accessed using their index, with the first element at index 0.

int[] arr = {10, 20, 30};
System.out.println("First element: " + arr[0]); 
// Outputs 10

3. Modifying Array Elements

You can change the value of an array element by assigning a new value to a specific index.

int[] arr = {10, 20, 30};
arr[1] = 25; 
// Changes the second element to 25

4. Displaying Array Elements

To display all elements of an array, you can use a loop to iterate through each index.

int[] arr = {10, 20, 30};
for (int i = 0; i < arr.length; i++) {
    System.out.println("Element at index " + i + ": " + arr[i]);
}

Code 1: Creation, Access, Modification, and Display

Run

public class ArrayOperations {
    public static void main(String[] args) {
        // Creating an array
        int[] numbers = new int[5]; // Declares and allocates memory for 5 elements

        // Modifying elements
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        // Accessing and displaying elements
        System.out.println("Accessing individual elements:");
        System.out.println("Element at index 0: " + numbers[0]);
        System.out.println("Element at index 3: " + numbers[3]);

        // Modifying a specific element
        System.out.println("\nModifying element at index 2...");
        numbers[2] = 35; // Changing value from 30 to 35

        // Displaying all elements
        System.out.println("\nDisplaying all array elements:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Output:

Accessing individual elements:
Element at index 0: 10
Element at index 3: 40

Modifying element at index 2...

Displaying all array elements:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 35
Element at index 3: 40
Element at index 4: 50

Modification of Arrays in Java

Code 2: Modification in User defined array

Problem Statement: Java Program to Print the Odd & Even Numbers in an Array

This is a Java Program to Print the Odd & Even Numbers in an Array.

Enter size of array and then enter all the elements of that array. Now using for loop and if condition we use to distinguish whether given integer in the array is odd or even.

Run
import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
        int n;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter no. of elements you want in array: ");
        n = s.nextInt();
        int a[] = new int[n];
        System.out.println("Enter all the elements: ");
        for (int i = 0; i < n; i++) 
        {
            a[i] = s.nextInt();
        }
        System.out.print("Odd numbers: ");
        for(int i = 0 ; i < n ; i++)
        {
            if(a[i] % 2 != 0)
            {
                System.out.print(a[i]+" ");
            }
        }
        System.out.println("");
        System.out.print("Even numbers: ");
        for(int i = 0 ; i < n ; i++)
        {
            if(a[i] % 2 == 0)
            {
                System.out.print(a[i]+" ");
            }
        }
    }
}

Output:

Enter No. of Elements you want in array: 5
Enter All the Elements:
1
2
3
4
5
Odd numbers: 1 3 5 
Even numbers: 2 4

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Other Important Operations related to Arrays in Java

1. Finding Array Length

The length of an array can be determined using the length property.

int[] arr = {10, 20, 30};
System.out.println("Array length: " + arr.length); // Outputs 3

2. Inserting Elements into an Array

Since arrays have a fixed size, inserting elements requires creating a new array with a larger size and copying existing elements.

int[] original = {10, 20, 30};
int[] newArray = new int[4];
for (int i = 0; i < original.length; i++) {
    newArray[i] = original[i];
}
newArray[3] = 40; // Inserting new element

3. Deleting Elements from an Array

To delete an element, you can shift subsequent elements to the left and reduce the array size.

Since arrays are fixed in size, this involves creating a new array.

int[] original = {10, 20, 30, 40};
int deleteIndex = 1;
int[] newArray = new int[original.length - 1];
for (int i = 0, k = 0; i < original.length; i++) {
    if (i == deleteIndex) {
        continue;
    }
    newArray[k++] = original[i];
}

4. Merging Arrays

To merge two arrays, you can create a new array with a size equal to the sum of the two arrays and copy elements from both.

int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] merged = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, merged, 0, arr1.length);
System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);

Code 3: For Finding, Inserting, Deleting and Merging Elements

Run

public class ArrayAdvancedOperations {
    public static void main(String[] args) {
        // Original array
        int[] original = {10, 20, 30, 40, 50};

        // Finding array length
        System.out.println("Original Array Length: " + original.length);

        // Inserting an element at the end
        int newElement = 60;
        int[] insertedArray = new int[original.length + 1];
        for (int i = 0; i < original.length; i++) {
            insertedArray[i] = original[i];
        }
        insertedArray[insertedArray.length - 1] = newElement;
        System.out.println("\nArray after inserting " + newElement + " at the end:");
        printArray(insertedArray);

        // Deleting an element (e.g., delete element at index 2)
        int deleteIndex = 2;
        int[] deletedArray = new int[insertedArray.length - 1];
        for (int i = 0, j = 0; i < insertedArray.length; i++) {
            if (i != deleteIndex) {
                deletedArray[j++] = insertedArray[i];
            }
        }
        System.out.println("\nArray after deleting element at index " + deleteIndex + ":");
        printArray(deletedArray);

        // Merging with another array
        int[] anotherArray = {70, 80, 90};
        int[] mergedArray = new int[deletedArray.length + anotherArray.length];

        for (int i = 0; i < deletedArray.length; i++) {
            mergedArray[i] = deletedArray[i];
        }
        for (int i = 0; i < anotherArray.length; i++) {
            mergedArray[deletedArray.length + i] = anotherArray[i];
        }
        System.out.println("\nArray after merging with {70, 80, 90}:");
        printArray(mergedArray);
    }

    // Helper method to print arrays
    public static void printArray(int[] arr) {
        for (int val : arr) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}

Output:

Original Array Length: 5

Array after inserting 60 at the end:
10 20 30 40 50 60 

Array after deleting element at index 2:
10 20 40 50 60 

Array after merging with {70, 80, 90}:
10 20 40 50 60 70 80 90 

Conclusion

  • Arrays in Java are one of the most essential and foundational data structures. They allow developers to store and manage a fixed number of elements of the same data type efficiently.
  • From creating arrays to accessing, modifying, inserting, deleting, and even merging arrays, mastering these operations is crucial for any Java programmer.
  • While arrays offer fast access and minimal overhead, their fixed size can sometimes be limiting. In such cases, dynamic structures like ArrayList or other collections from the Java Collections Framework become more suitable.

However, a solid understanding of how arrays work internally helps in building a strong programming foundation and writing optimized code.

Whether you’re preparing for coding interviews, building projects, or just learning Java, working with arrays is a key skill that unlocks your ability to handle linear data structures, implement algorithms, and solve complex problems effectively.

Learn DSA

FAQ's Related to Arrays in Java

Answer:

An array in Java is a container object that holds a fixed number of values of the same data type. Each element can be accessed using an index, starting from 0.

Answer:

No, arrays in Java are fixed in size. Once an array is created, its length cannot be modified. To work with a resizable array, use data structures like ArrayList.

Answer:

Accessing an index that is out of bounds throws an ArrayIndexOutOfBoundsException, which is a runtime exception in Java.

Answer:

  • single-dimensional array stores elements in a linear form.
  • multi-dimensional array (like a 2D array) stores elements in a table-like structure with rows and columns.

 

Answer:

  • Traditional for loop using indices
  • An enhanced for-each loop for simplicity
  • A while loop in specific cases

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

3 comments on “Arrays in Java”