Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is an Array in Java?
2.1.
Advantages
2.2.
Disadvantages
3.
Types of Array in Java
4.
Single-Dimensional Array in Java
4.1.
Declaration, Instantiation, and Initialization of Java Array
4.1.1.
Syntax
4.1.2.
Example:
4.2.
Instantiation
4.2.1.
Syntax:
4.2.2.
Example: 
4.3.
Initialization
4.3.1.
Example:
4.3.2.
Code
4.3.3.
Example 
5.
Multi-Dimensional Arrays
5.1.
Syntax
5.2.
Example of Multidimensional Java Array
6.
For-each Loop for Java Array
7.
Passing An Array In Java 
8.
Creating an Array of Objects
9.
Array Index Out Of Bounds Exception
10.
Frequently Asked Questions
10.1.
Is array a variable in Java?
10.2.
What is Java Array?
10.3.
What is an example of a 1d array in Java?
10.4.
Is array 0 or 1 Java?
10.5.
How many types of arrays are there in Java?
10.6.
How to declare an array?
11.
Conclusion
Last Updated: Jul 13, 2024
Easy

Arrays In Java

Author Lokesh Sharma
2 upvotes

Introduction

Arrays in Java 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.

Advantages

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

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 Array 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.

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[];  
You can also try this code with Online Java Compiler
Run Code

 

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

Example:

int[] intArray; // Declare an integer array
You can also try this code with Online Java Compiler
Run Code

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];
You can also try this code with Online Java Compiler
Run Code

 

Example: 

int[] intArray; // Declare an integer array
intArray = new int[5]; // Instantiate the integer array of size 5
You can also try this code with Online Java Compiler
Run Code

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}; 
You can also try this code with Online Java Compiler
Run Code

 

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;
You can also try this code with Online Java Compiler
Run Code
example array

 

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

Code

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
You can also try this code with Online Java Compiler
Run Code

 

Example 

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

for (int i = 0; i < intArray.length; i++) {
    System.out.println(intArray[i]);
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

1
2
3
4
5
You can also try this code with Online Java Compiler
Run Code

 

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.

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

<data-type>[][] <variable-name>
You can also try this code with Online Java Compiler
Run Code


Or

<data-type> <variable-name>[][]
You can also try this code with Online Java Compiler
Run Code


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

int[][] twoDArray = new int[3][4];
You can also try this code with Online Java Compiler
Run Code

 

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 also try this code with Online Java Compiler
Run Code

 

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();
}
You can also try this code with Online Java Compiler
Run Code

 

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

int[][][] threeDArray = new int[3][3][3];
You can also try this code with Online Java Compiler
Run Code

 

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();
}
You can also try this code with Online Java Compiler
Run Code

 

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. 

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 
You can also try this code with Online Java Compiler
Run Code


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.

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
}
You can also try this code with Online Java Compiler
Run Code


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
You can also try this code with Online Java Compiler
Run Code


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:

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
You can also try this code with Online Java Compiler
Run Code

 

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:

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
You can also try this code with Online Java Compiler
Run Code

 

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];
You can also try this code with Online Java Compiler
Run Code

 

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 try this code with Online Java Compiler
Run Code

 

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());
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Ninja1
Ninja2
Ninja3
Ninja4
Ninja5
You can also try this code with Online Java Compiler
Run Code

 

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
You can also try this code with Online Java Compiler
Run Code

 

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 bound

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
You can also try this code with Online Java Compiler
Run Code

 

Must Read Type Conversion in Java

Frequently Asked Questions

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 Java Array?

A Java array is a data structure that stores a fixed number of elements of the same type, accessible via indexed positions.

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.

Is array 0 or 1 Java?

In Java, arrays are zero-indexed, meaning the first element is accessed with index 0.

How many types of arrays are there in Java?

Java supports two types of arrays: single-dimensional arrays and multi-dimensional arrays (e.g., 2D arrays).

How to declare an array?

An array in Java is declared by specifying the type and using square brackets, e.g., int[] myArray;.

Conclusion

In this article, we learned about Array in Java. We saw how 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 more easier.

We hope you enjoyed reading this article. If you wish to learn more about arrays and java, refer to the following blogs.

Live masterclass