Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for managing collections of data efficiently. Arrays in Java work differently than they do in C/C++. This article covers the basics and in-depth explanations with examples of array declaration , creation , and manipulation in Java.
Table of Content
To declare an array in Java, use the following syntax:
type[] arrayName;
Here’s an example of declaring an integer array:
int[] numbers; // Declaring an integer array
To create an array, you need to allocate memory for it using the new keyword :
numbers = new int[5]; // Creating an array of 5 integers
We can access array elements using their index, which starts from 0 :
numbers[0] = 10; // Setting the first element of the array
int firstElement = numbers[0]; // Accessing the first element
To change an element, assign a new value to a specific index:
numbers[0] = 20; // Changing the first element to 20
We can get the length of an array using the length property:
int length = numbers.length; // Getting the length of the array
This retrieves the number of elements in the numbers array, which is 5 in this case.
The above are the basic details of Arrays in Java. Now, if you want to go through the in-depth concepts of Java Arrays , then scroll down below and go through the diagrams, examples, and explanations.
Following are some important points about Java arrays.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class, depending on the definition of the array. In the case of primitive data types, the actual values might be stored in contiguous memory locations (JVM does not guarantee this behavior). In the case of class objects, the actual objects are stored in a heap segment . To learn more about Java Array, go through Java programming course here.
Note: This storage of arrays helps us randomly access the elements of an array [Support Random Access].
The general form of array declaration is
-- type var-name[];
-- type[] var-name;
// both are valid declarations
int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;
When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate.
//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Do refer to default array values in Java .
Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java , all arrays are dynamically allocated.
In a situation where the size of the array and variables of the array are already known, array literals can be used.
// Declaring array literal
int[] intArray = new int[]< 1,2,3,4,5,6,7,8,9,10 >;
Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
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
Time Complexity: O(n)
Auxiliary Space: O(1)
Java supports different types of arrays:
These are the most common type of arrays, where elements are stored in a linear order.
int[] singleDimArray = ; // A single-dimensional array
Arrays with more than one dimension, such as two-dimensional arrays (matrices).
int[][] multiDimArray =
,
,
>; // A 2D array (matrix)
You can also access java arrays using for each loops .
An array of objects is created like an array of primitive-type data items in the following way.
Student[] arr = new Student[5]; //Student is a user-defined class
-- data type[] arrName;
-- datatype arrName[];
-- datatype [] arrName;
Below is the implementation of the above mentioned topic:
Array Size:4
Below is the implementation of the above mentioned topic:
Element at 0 : 1 aman Element at 1 : 2 vaibhav Element at 2 : 3 shikar Element at 3 : 4 dharmesh Element at 4 : 5 mohit
Time Complexity: O(n)
Auxiliary Space : O(1)
An array of objects is also created like :
Dharma sanvi Rupa Ajay
JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array.
Below code shows what happens if we try to access elements outside the array size:
Output
Trying to access element outside the size of array
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
at GFG.main(GFG.java:13)
10 20
Time Complexity: O(n), here n is size of array.
Auxiliary Space: O(1) , since no extra space required.
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays. These are also known as Jagged Arrays . A multidimensional array is created by appending one set of square brackets ([]) per dimension.
There are 2 methods to declare Java Multidimensional Arrays as mentioned below:
datatype [][] arrayrefvariable;
datatype arrayrefvariable[][];
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Number of Rows:3 Number of Columns:3
2 7 9 3 6 1 7 4 2
Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate the sum of the array’s values.
sum of array values : 15
Time Complexity: O(n)
Auxiliary Space : O(1)
As usual, a method can also return an array. For example, the below program returns an array from method m1 .
1 2 3
Time Complexity: O(n)
Auxiliary Space : O(1)
Every array has an associated Class object, shared with all other arrays with the same component type.
class [I class java.lang.Object class [B class [S class [Ljava.lang.String;
Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class Object. The members of an array type are all of the following:
Array Types | Allowed Element Types |
---|---|
Primitive Type Arrays | Any type which can be implicitly promoted to declared type. |
Object Type Arrays | Either declared type objects or it’s child class objects. |
Abstract Class Type Arrays | Its child-class objects are allowed. |
Interface Type Arrays | Its implementation class objects are allowed. |
When you clone a single-dimensional array, such as Object[] , a shallow copy is performed. This means that the new array contains references to the original array’s elements rather than copies of the objects themselves. A deep copy occurs only with arrays containing primitive data types, where the actual values are copied.
false 1 2 3
A clone of a multi-dimensional array (like Object[][]) is a “shallow copy,” however, which is to say that it creates only a single new array with each element array a reference to an original element array, but subarrays are shared.
false true true
Yes, Java supports arrays of primitive types such as int , char , boolean , etc., as well as arrays of objects.
Multidimensional arrays in Java are represented as arrays of arrays. For example, a two-dimensional array is declared as int[][] array , and it is effectively an array where each element is another array.
No, the size of an array in Java cannot be changed once it is initialized. Arrays are fixed-size. To work with a dynamically sized collection, consider using classes from the java.util package, such as ArrayList .
No, we cannot specify the size of an array as long . The size of an array must be specified as an int . If a larger size is required, it must be handled using collections or other data structures.
The direct superclass of an array in Java is Object . Arrays inherit methods from the Object class, including toString() , equals() , and hashCode() .