Java array is an object that contains elements of similar datatype since it is an object we cannot use member length to find the array length
Array can be declared like any other variable with datatype and name followed by []
The size of the array should be specified initially in int which cannot be increased during runtime which is identified as one of the setbacks while using an array
Array indices
Array performs index-based operations. An array can be considered as below
Where 0,1,2…. are the indexes of an array. If the size of the array is n the indexes of the array would be counted from n-1
There are two types of array
-> Single dimensional array
-> Multidimensional array
One dimensional array represents one row or one column of array elements distinguished by index values
An array can be declared in any of the following ways
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Where datatype can be a primitive data type like int, char, Double, byte, etc. and arr is an identifier representing the array name.
When an array is declared, only a reference of an array is created. To create or give memory to an array, you create an array below
arr-name = new type [size];
Where arr-name is a reference variable for the array, type specifies the type of data being allocated, size specifies the number of elements in the array
The elements in the array allocated by new will automatically be initialized to the default assigned values of the array as follows
-> boolean :false
-> int : 0
-> double : 0.0
-> String :null
-> User Defined Type :null
Use case demonstrating declaration, instantiation, and initialization of an array
Output:
There is also a "for-each" loop, which is used exclusively to loop through elements in an array
Syntax
use case demonstrating usage of for each to iterate the array
Output:
Output:
Multidimensional arrays are arrays with each element of the array holding the reference of another array. The syntax to declare a multidimensional array is as follows
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Use case demonstrating multidimensional array
Output:
It is one of the common exceptions whenever we are handling an array.JVM throws this exception when the array size is negative or equal to more than the declared size of an array.