Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Java Arrays?
2.1.
Advantages
2.2.
Disadvantages
3.
Types of Array in Java
4.
One-Dimensional Array in Java
4.1.
Declaration
4.2.
Instantiation
4.3.
Initialization
4.4.
Code
4.5.
Example 
5.
For-each Loop for Java Array
6.
Passing An Array In Java 
7.
Creating an Array of Objects
8.
Array Index Out Of Bounds Exception
9.
Multi-Dimensional Arrays
9.1.
Syntax
9.2.
Example of Multidimensional Java Array
10.
Frequently Asked Questions
10.1.
What is a array in Java?
10.2.
What is the syntax for declaring an array in Java?
10.3.
Is array a variable in Java?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Arrays In Java

Author Lokesh Sharma
1 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java Arrays is a data structure that is used to store a fixed number of elements of the same data type. Java Arrays are created using the new keyword and the {} braces. 

In this article, we'll cover everything from the basics of array creation to manipulating and sorting data. So don't miss out on the chance to take your Java skills to the next level.

Array in Java

Let us start by understanding what arrays in Java are.

What is Java Arrays?

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

One-Dimensional Array in Java

These arrays are one-dimensional and are more commonly used. 

Let us see how to declare, instantiate and initialise a 1-D array in java.

Declaration

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

 

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.

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:

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

 

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:

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] + " ");
    }
}

 

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

 

Must Read Type Conversion in Java

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>


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. 

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

	}
}


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.
 

Must Read Conditional Statements in Java 

Frequently Asked Questions

What is a array in Java?

An array in Java is a data structure used to store elements of the same data type, and it can store a fixed number of elements. Arrays are declared using the [] brackets.

What is the syntax for declaring an array in Java?

The syntax in Java is dataType[] arrayName = new dataType[] {element1, element2, ...}

Here the datatype is the type of data like int, char etc., and the arrayName is the name of the array variable. The new keyword creates a new array object. The {} braces contain the elements of the array. 

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.

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.

Previous article
What is Array
Next article
Single Dimensional Array
Live masterclass