Java Arrays - The Coding Shala
Home >> Learn Java >> Java Arrays
An array is a collection of the same data type variables. We can access and store the variables in an array by its index. In Java, arrays may have one or more dimensions like a 1-D array, 2-D arrays or multi-Dimensional arrays.
Java One-Dimensional Arrays(1-D Array)
The basic syntax to declare Java 1-D array is as follows -
Here, type declares the data type of the array means which type of data is going to store inside the array. For example -
Here, an array named arr is created having type int. We can store integer values inside arr.
Here, array_name is set to null which means an array with no value. A new operator is used to allocate memory to the array so the basic syntax is as follows -
Here, the size specified the numbers of elements in the array. We can access a specified element in the array by specifying its index within the square bracket.
In Java, all array indexes start at zero. Arrays can be initialized when they are declared. To initialize the array we have to assign a list of comma-separated data or expressions surrounded by curly braces. There is no need to use new in this case.
The following Java program demonstrates the 1-D array -
Java Multidimensional Arrays
In Java, multidimensional arrays are arrays of arrays. The following syntax is used to declare a 2-D array -
Similar we can also declare 3-D array -
The following example explains Java 2-D array -
When we allocate memory for the multi-dimensional array, we need to specify the memory for the first(leftmost) dimension. For the remaining dimensions, we can allocate separately. For example -
Other Posts You May Like