Table of contents
1.
Introduction
2.
What is an Array in Java?
3.
Syntax of Arrays in Java
3.1.
Declaring an Array
3.2.
Creating an Array
3.3.
Declaring and Creating an Array in One Step
3.4.
Initializing an Array with Values
4.
Declare an Array in Java
5.
Initializing an Array
6.
Accessing an Array
7.
Key Features of Arrays in Java
8.
Array Properties in Java
9.
Advantages of Java Arrays
10.
Disadvantages of Java Arrays
11.
Types of Arrays in Java
11.1.
1. Single-Dimensional Array in Java
11.1.1.
Instantiation
11.1.2.
Initialization
11.2.
Java
11.3.
2. Multi-Dimensional Arrays
11.3.1.
Syntax of Multi-Dimensional Arrays
11.3.2.
Example of Multidimensional Java Array
11.4.
Java
12.
Useful Operations on Arrays in Java
12.1.
Addition using Java Arrays
12.2.
Multiplication using Java Arrays
12.3.
Copying using Java Arrays
12.4.
Cloning using Java Arrays
12.5.
Binary Search Using Java Arrays
12.6.
For-each Loop for Java Array
12.7.
Passing An Array In Java 
12.8.
Java
12.9.
Java
12.10.
Creating an Array of Objects
12.11.
Array Index Out Of Bounds Exception
13.
Overview of Utility Class
14.
Arrays vs ArrayList
14.1.
Key Differences
14.2.
When to Use Arrays vs ArrayList?
15.
Real-World Use Cases of Arrays
15.1.
Storing User Inputs
15.2.
Managing Game Scores or Grades
15.3.
Use in Algorithms (like Sorting and Searching)
16.
Frequently Asked Questions
16.1.
What is array in Java class?
16.2.
Is array a variable in Java?
16.3.
What is an example of a 1d array in Java?
16.4.
Why do we declare arrays?
16.5.
Can we change the size of an array in Java?
16.6.
Can arrays hold different data types?
17.
Conclusion
Last Updated: Sep 22, 2025
Easy

Java Arrays

Author Lokesh Sharma
7 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java arrays are fundamental data structures that store fixed-size sequential collections of elements of the same type. They provide a simple way to manage multiple values efficiently. Arrays are indexed, allowing quick access and modification of elements. They are essential for handling lists of data, enabling effective storage and retrieval. Understanding arrays is crucial for mastering Java programming and building more complex data structures.

Array in Java

What is an Array in Java?

An Array in Java is a collection of similar elements with a contiguous memory location. It is used to store multiple values in a single variable instead of declaring separate variables for each value. Arrays are indexed, meaning each array element has a specific position (also called index) that is used to access it. The index of an array always starts from 0.

Syntax of Arrays in Java

Declaring an Array

dataType[] arrayName; // Preferred syntax
dataType arrayName[]; // Also valid, but less common

Creating an Array

arrayName = new dataType[size];

Declaring and Creating an Array in One Step

dataType[] arrayName = new dataType[size];

Initializing an Array with Values

dataType[] arrayName = {value1, value2, value3, ...};

Declare an Array in Java

In Java, an array is declared to store multiple elements of the same data type in a single variable. The syntax involves specifying the data type, followed by square brackets ([]) and the array name.

You can declare an array like this:

int[] numbers; // Preferred way
int numbers[]; // Also valid

 

The declaration only reserves space for the reference to the array, not the actual elements. To use it, you must initialize it with a size or values.

numbers = new int[5]; // Allocates memory for 5 integers

Initializing an Array

Initializing an array means creating an array and optionally assigning values to its elements. In Java, you can initialize an array in two ways:

1. Declaration with size:

int[] numbers = new int[5]; // Creates an array of size 5 with default values (0)

 

2. Declaration with values:

int[] numbers = {1, 2, 3, 4, 5}; // Directly initializes the array with values

 

When you initialize an array, Java automatically assigns default values based on the data type (e.g., 0 for integers, null for objects).

Accessing an Array

Accessing an array means retrieving or modifying the value of a specific element using its index. Array indices in Java start from 0.
Example:

int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[2]); // Outputs 30 (element at index 2)
numbers[1] = 25; // Updates the element at index 1 to 25 

You can access any array element using the syntax: arrayName[index].

Key Features of Arrays in Java

  • Contiguous Memory Allocation (for Primitives)
    In Java, primitive arrays (like int[]) are stored in contiguous memory blocks. This improves performance and allows direct access using the index.
     Example:
int[] nums = {10, 20, 30}; // stored in a continuous block

 

  • Zero-based Indexing
    Java arrays start at index 0. This means the first element is accessed using array[0]. It’s important when using loops to avoid ArrayIndexOutOfBoundsException.
     Example:
System.out.println(nums[0]); // prints 10

 

  • Fixed Length
    Once an array is created, its size cannot be changed. You must know the number of elements beforehand or use dynamic structures like ArrayList.
     Example:
int[] a = new int[5]; // size is fixed to 5

 

  • Ability to Store Both Primitives and Objects
    Arrays in Java can store primitive types (int, double) and object references (String, Integer, etc.). This makes arrays versatile for different data needs.
     Example:
String[] names = {"Alice", "Bob"};

Array Properties in Java

  • Arrays are Dynamically Allocated
    Java arrays are allocated on the heap at runtime using the new keyword. This allows more flexible memory management compared to static arrays in some other languages.
     Example:
int[] arr = new int[5]; // memory allocated dynamically

 

  • Arrays May Be Stored in Contiguous Memory
    Arrays storing primitives typically occupy a continuous block in memory, which makes index-based access faster. For objects, the references are stored contiguously.
     
  • Use of .length Property to Get Array Size
    Java arrays include a built-in .length field (not method) that returns the total number of elements.
     Example:
System.out.println(arr.length); // prints 5

 

  • Array Declaration Syntax
    Java supports multiple syntax formats to declare arrays. Commonly used is type[] name.
     Example:
int[] data; // preferred  
int data[]; // also valid

 

  • Ordered Index Starting from 0
    Every element in the array is accessed using a numbered index that starts at 0 and goes up to array.length - 1, maintaining order and consistency.
     
  • Arrays Used as Static Fields, Local Variables, or Method Parameters
    Arrays in Java can be declared at any scope: class-level (static), inside methods, or as parameters.
     Example:
static int[] staticArray = new int[3];

 

  • Ability to Store Both Primitive Types and Object References
    Arrays can hold either data types like int[] or reference types like String[]. This makes them useful in a wide range of Java applications.

Advantages of Java Arrays

Arrays in Java have several advantages, including:

  1. Efficient Access: Arrays are stored in contiguous memory locations, which allows for fast and efficient access to elements using their index.
     
  2. Code Simplicity: Arrays can be used to store and manipulate large amounts of data in a simple and organized way.
     
  3. Easy Iteration: Arrays can be easily iterated over using the enhanced for loop (for-each loop), making it easy to perform operations on all elements in the array.
     
  4. Built-in Methods: Java provides the Arrays class, which has several useful methods for working with arrays, such as sorting, searching, and filling elements with a specific value.
     
  5. Memory Management: Java's built-in garbage collector automatically frees up memory that is no longer in use, which helps to prevent memory leaks.
     
  6. Bounds Checking: Java arrays have built-in bounds checking, which helps to prevent buffer overflow issues and makes it easier to write safe and secure code.
     
  7. Multi-dimensional Arrays: Java allows the creation of multi-dimensional arrays, which makes it easy to represent and manipulate data in a structured way.

Disadvantages of Java Arrays

An array in Java is a very useful tool. But it, too, has its own limitations.

  1. Fixed Size: Once an array is created, its size cannot be changed. This can be a disadvantage if the size of the array needs to be increased or decreased during the execution of the program.
     
  2. Extra Space: When creating a new array with a larger size, a new array must be created, and the elements from the old array must be copied over. This can lead to extra space being used and can be inefficient.
     
  3. Homogeneous Data: All elements in an array must be of the same data type, which can be limiting in some situations.
     
  4. Type-Casting: If the elements of an array are of different data types, they must be type-casted before being used, which can lead to runtime errors.
     
  5. Initialization: Arrays need to be initialized before they can be used, which can take extra time and effort.
     

Also see, Swap Function in Java

Types of Arrays in Java

There are two types of arrays in Java. 

  1. One-Dimensional Arrays.
  2. Multi-Dimensional Arrays.
     

We will discuss both of these in detail.

1. Single-Dimensional Array in Java

Declaration, Instantiation, and Initialization of Java Array

You can declare an array using three simple ways.

Syntax

dataType[] arr;
dataType []arr;
dataType arr[];  

 

All the above three formats are correct, and any one can be used. 

Example:

int[] intArray; // Declare an integer array

Instantiation

Just declaring an array does not create an actual array. This means that no memory is provided to the array. To provide memory and create an array, we instantiate it. To instantiate an array, you use the 'new' keyword followed by the type of the elements, and the size of the array in square brackets. 

Syntax:

<variable_name> = new <data-type> [size];

 

Example: 

int[] intArray; // Declare an integer array
intArray = new int[5]; // Instantiate the integer array of size 5

Initialization

Initialization means assigning values to the array elements. To initialize an array, you can use an array literal or assign values to each element of the array.

Example:

// Initialize an integer array using array literal
int[] intArray = {1, 2, 3, 4, 5}; 

 

Or

int[] intArray = new int[5];
// Initialize array using index
intArray[0] = 1;
intArray[1] = 2;
intArray[2] = 3;
intArray[3] = 4;
intArray[4] = 5;
Single-Dimensional Array in Java

 

Here is a complete, executable java code demonstrating the declaration, instantiation, and initialization of an array in java.

Code

  • Java

Java

public class ArrayExample {
   public static void main(String[] args) {


       // Declare an array variable
       int[] numbers;
      
       // Instantiate the array
       numbers = new int[5];


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


       // Print the array elements
       for (int i = 0; i < numbers.length; i++) {
           System.out.println("Element at index " + i + ": " + numbers[i]);
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

Output:

Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

 

Example 

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

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

 

Output:

1
2
3
4
5

 

In this example, the variable i is used as the index to access each element in the intArray. The loop starts with i equal to 0 and continues until i is less than the length of the intArray, incrementing i by 1 in each iteration. The length property of the intArray is used to determine the number of iterations.

2. Multi-Dimensional Arrays

In Java, a multidimensional array is an array of arrays. It is a data structure that allows you to store multiple arrays in a single array. The most common types of multidimensional arrays are two-dimensional (2D) and three-dimensional (3D) arrays, but Java also supports arrays with more than three dimensions. These types of arrays are also known as jagged arrays.

A 2D array is an array of arrays, where each array represents a row of the 2D array. A 3D array is an array of 2D arrays, where each 2D array represents a plane of the 3D array.

Syntax of Multi-Dimensional Arrays

<data-type>[][] <variable-name>


Or

<data-type> <variable-name>[][]


Here's an example of how to declare and initialize a 2D array in Java:

int[][] twoDArray = new int[3][4];

 

In this example, twoDArray is a 2D array of integers with 3 rows and 4 columns.

You can also initialize the elements of a 2D array at the time of declaration like this:

int[][] twoDArray = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

 

You can access the elements of a 2D array using a nested for loop. Here's an example:

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

 

Similarly, you can create and access 3D array and more dimensional arrays as well.

int[][][] threeDArray = new int[3][3][3];

 

To access the elements of a 3D array, you would use a nested for loop like this:

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

 

Also, note that Java also supports the use of a for-each loop to iterate over multidimensional arrays. But it will be nested as many times as the dimension of the array is.

Multidimensional arrays in Java are useful when you need to store and work with large amounts of data that can be organized into a grid or matrix. They allow you to represent and access data in a more organized way, making it easier to understand and work with.

Must Read Array of Objects in Java

Example of Multidimensional Java Array

In this example, we are creating a 2D array containing integers. 

  • Java

Java

class CodingNinjas {
static int MAX = 100;
static void printDiagonal(int mat[][], int n)
{
System.out.print("Diagonal: ");

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {

// Condition
if (i == j) {
System.out.print(mat[i][j] + " ");
}
}
}
System.out.println("");
}

public static void main(String args[])
{
int n = 4;
int a[][] = { { 10, 2, 3, 4 },
{ 5, 60, 7, 8 },
{ 1, 2, 30, 4 },
{ 5, 6, 7, 80 } };

printDiagonal(a, n);

}
}
You can also try this code with Online Java Compiler
Run Code


Output:

Diagonal: 10 60 30 80 


Here in the above code, we have traversed the 2D array and printed out only the diagonal elements by using the i==j condition. We call the printDiagonal() function that takes two parameters that are a denotes the Multidimensional array, and n denotes the column and row size.

Useful Operations on Arrays in Java

Addition using Java Arrays

You can add corresponding elements of two arrays using a loop.

int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] result = new int[3];

for (int i = 0; i < arr1.length; i++) {
    result[i] = arr1[i] + arr2[i];
}

System.out.println(Arrays.toString(result));  // Output: [5, 7, 9]

Multiplication using Java Arrays

Multiply corresponding elements of two arrays using a loop.

int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] result = new int[3];

for (int i = 0; i < arr1.length; i++) {
    result[i] = arr1[i] * arr2[i];
}

System.out.println(Arrays.toString(result));  // Output: [4, 10, 18]

Copying using Java Arrays

Use System.arraycopy() or Arrays.copyOf() to copy an array.

int[] arr = {1, 2, 3};
int[] copy = Arrays.copyOf(arr, arr.length);

System.out.println(Arrays.toString(copy));  // Output: [1, 2, 3]

Cloning using Java Arrays

Arrays in Java can be cloned using the clone() method.

int[] arr = {1, 2, 3};
int[] cloneArr = arr.clone();

System.out.println(Arrays.toString(cloneArr));  // Output: [1, 2, 3]

Binary Search Using Java Arrays

Use Arrays.binarySearch() to find the index of an element in a sorted array.

int[] arr = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(arr, 3);

System.out.println(index);  // Output: 2

For-each Loop for Java Array

A For-each is a special type of loop that is used to iterate over the elements of an array. They are often used in place of traditional loops when we only need to access each element of the array once.

The basic syntax for each loop is as follows:

for (element : array) {
 // Do something with element
}


Here's an example of how to print the element of an array using for-each loop in Java:

Code:

String[][] array = new String[][] {{"a", "b", "c"}, {"d", "e", "f"}};

for (String[] row : array) {
  for (String element : row) {
    System.out.println(element);
  }
}

 

Output:

a
b
c
d
e
f


In this example, the 2d Array of strings is been declared, and then using the for each loop, each element in the 2d array is printed in a separate line.

Passing An Array In Java 

Many times, you may need to pass an array to a method in java and perform some useful operation. In Java, arrays are objects and are passed to methods by reference. This means that when you pass an array to a method, the method receives a reference to the memory location where the array is stored, rather than a copy of the array.

Here's an example of how to pass an array to a method in Java:

Code:

  • Java

Java

public static void printArray(int[] arr) {
   for (int i = 0; i < arr.length; i++) {
       System.out.print(arr[i] + " ");
   }
   System.out.println();
}


public static void main(String[] args) {
   int[] myArray = {1, 2, 3, 4, 5};
   printArray(myArray);
}
You can also try this code with Online Java Compiler
Run Code

Output:

1 2 3 4 5

 

In this example, the printArray method takes an int array as its parameter and prints its elements to the console. The main method creates an int array and passes it to the printArray method.

Also note that, when you pass an array to a method, you can modify its elements inside the method, and those changes will be reflected in the original array. Here's an example:

Code:

  • Java

Java

public static void modifyArray(int[] arr) {
   for (int i = 0; i < arr.length; i++) {
       arr[i] = arr[i] * 2;
   }
}


public static void main(String[] args) {
   int[] myArray = {1, 2, 3, 4, 5};
   modifyArray(myArray);
   for (int i = 0; i < myArray.length; i++) {
       System.out.print(myArray[i] + " ");
   }
}
You can also try this code with Online Java Compiler
Run Code

Output:

2 4 6 8 10

 

In this example, the modifyArray method multiplies the elements of the array by 2, and the main method prints the modified array.

Creating an Array of Objects

You can create an array of non-primitive data types in java, just the same way as you create an array for primitive data types. Consider the following example for better understanding.

Code

class CodingNinja {
    private int id;
    private String name;

    public CodingNinja(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

CodingNinja[] ninjaArray = new CodingNinja[5];

 

In this example, the array ninjaArray has been declared as an array of CodingNinja objects, with a size of 5. Note that this array has only been declared but not instantiated.

You can initialize the array elements by creating new objects of the CodingNinja class, and then storing them at the corresponding index in the array.

Code:

ninjaArray[0] = new CodingNinja(1, "Lokesh");
ninjaArray[1] = new CodingNinja(2, "Rohit");
ninjaArray[2] = new CodingNinja(3, "Varun");
ninjaArray[3] = new CodingNinja(4, "Priyanka");
ninjaArray[4] = new CodingNinja(5, "Sakshi");

 

You can also use a loop to initialize the array:

Code:

for (int i = 0; i < ninjaArray.length; i++) {
    ninjaArray[i] = new CodingNinja(i + 1, "Ninja " + (i + 1));
    System.out.println(ninjaArray[i].getName());
}

 

Output:

Ninja1
Ninja2
Ninja3
Ninja4
Ninja5

 

It's important to note that when you declare an array of objects, Java creates an array of references to the objects, not the objects themselves. So, when you create new objects and assign them to the array elements, you're actually storing references to the objects in the array.

Array Index Out Of Bounds Exception

“ArrayIndexOutOfBoundsException” is a runtime exception that occurs in Java when a program attempts to access an array index that is outside the bounds of the array. In other words, it occurs when the program tries to access an index that is either less than 0 or greater than or equal to the length of the array.

Here is an example of how this exception can be thrown:

Code:

int[] numbers = new int[5];
numbers[5] = 10; // throws ArrayIndexOutOfBoundsException

 

In the above example, the array "numbers" has a length of 5, so the valid indices are 0, 1, 2, 3, and 4. However, the program is trying to access index 5, which is outside the bounds of the array and therefore throws an ArrayIndexOutOfBoundsException.

Array Index Out Of Bounds Exception

This exception can also occur when trying to access a negative index, for example:

Code:

int[] numbers = new int[5];
numbers[-1] = 10; // throws ArrayIndexOutOfBoundsException

 

Must Read Type Conversion in Java

Overview of Utility Class

The java.util.Arrays class is a utility class that provides static methods for efficiently working with arrays. It simplifies common tasks such as sorting, searching, comparing, filling, and converting arrays. This helps developers avoid writing repetitive code and ensures optimal performance.

Example use case:
Sorting an integer array with Arrays.sort(myArray) is faster and simpler than implementing your own sort logic.

Arrays vs ArrayList

Key Differences

FeatureArraysArrayList
SizeFixed at creationDynamic – grows/shrinks automatically
PerformanceSlightly faster due to no overheadSlightly slower due to dynamic resizing
Type RestrictionsCan store primitive types (e.g., int)Stores only objects (e.g., Integer)
Memory UsageMore memory-efficientSlightly higher memory footprint
Syntax SimplicityVerbose (manual resizing, looping)Cleaner API with built-in methods

When to Use Arrays vs ArrayList?

Use Arrays When:

  1. Fixed-size data is known
    Arrays are ideal when you know the number of elements in advance (e.g., days in a week).
  2. Performance-critical applications
    Arrays perform slightly better in tight loops or real-time systems due to minimal overhead.
  3. Storing primitive types
    Prefer arrays when dealing with primitives like int or char to avoid boxing overhead.
  4. Use ArrayLists When:
  5. Dynamic data structures
    Use ArrayList when the number of elements can change at runtime (e.g., user-generated items).
  6. Frequent insertions/deletions
    ArrayLists provide flexible methods like add() and remove() for easy manipulation.
  7. Built-in utility methods are needed
    Methods like contains(), indexOf(), and isEmpty() simplify code when working with collections.

Real-World Use Cases of Arrays

Storing User Inputs

Arrays are often used to temporarily store user inputs (e.g., survey ratings or login attempts). Since the number of inputs may be fixed (e.g., 5-star ratings), arrays offer a simple, fast structure to hold this data.

Managing Game Scores or Grades

Games and educational platforms use arrays to store scores or grades. For example, a game might track the top 10 scores using an array. This allows fast access and sorting, making it ideal for leaderboards.

Use in Algorithms (like Sorting and Searching)

Arrays are foundational in algorithms involving sorting (e.g., quicksort) and searching (e.g., binary search). Their fixed size and indexed access make them efficient and predictable for algorithmic operations, especially in time-critical systems.

Frequently Asked Questions

What is array in Java class?

An array in Java is a fixed-size, indexed collection of elements of the same data type, used to store multiple values efficiently.

Is array a variable in Java?

An array is not a variable in Java, but it is a data structure that is used to store elements of the same data type. The elements can be integers, characters or strings etc., and the array is of fixed size.

What is an example of a 1d array in Java?

An example of a 1D array in Java is int[] numbers = {1, 2, 3, 4, 5};, which stores integer values in a single row.

Why do we declare arrays?

Arrays are declared in Java to store multiple values of the same data type in a single variable. This allows efficient access, organization, and management of large collections of data.

Can we change the size of an array in Java?

No, arrays in Java have a fixed size once they are created. To "resize" an array, you would need to create a new array with the desired size and copy the elements from the old array.

Can arrays hold different data types?

No, traditional arrays in Java can only hold elements of the same data type. However, you can use an Object[] array, which can store objects of different types, but this requires type casting.

Conclusion

In this article, we learned about arrays in Java. We saw how an array is useful to organize and store similar types of data. We also discussed how to access elements of an array. Overall, an array in Java is a fantastic tool that makes storing and accessing data a lot easier.

Recommended Readings:

Live masterclass