![]() |
VOOZH | about |
In Java, an Array is used to store multiple values of the same type in a single variable. There are two types of arrays in Java:
In this article, we are going to discuss how to declare and use single and multidimensional arrays in Java.
It is a collection of variables of the same type which is used by a common name. In an array, we can access each element with the help of an index.
The declaration of a single-dimensional array is:
dataType[] arrayName = new dataType[size];
Note: Here, dataType is the type of elements the array will store, arrayName is the name of the array variable, and size is the number of elements the array can hold.
Example:
We can write it in any way. Now, if declare the array like below:
Example:
Now, suppose we want to write multiple declaration of array variable then how we gonna do this.
Example:
When we are declaring multiple variable of same time at a time, we have to write variable first then declare that variable except first variable declaration. There is no restriction for the first variable.
Note: When we creates an array it is mandatory to pass the size of array, otherwise we will get compile time error. We can use new operator for creating an array.
Example:
100 100 100
Now, we will discuss about Multidimensional Array in detail.
Suppose, we want to create mutli dimensional array of int data type.
The declaration of multidimensional array is:
dataType[][] arrayName = new dataType[rows][columns];
Note: Here, row is the number of rows and coloumn is the number of element in each row.
So, there are multiple ways to declare multidimensional array which are below with examples:
Example:
Now, suppose we want to write multiple declarations of array variable then we can use it like this.
Example:
Element at position (0,0): 100 Element at position (0,1): 100 Element at position (0,2): 100 Element at position (1,0): 100 Element at position (1,1): 100 Element at position (1,2): 100
Now, we are going to disucuss one more interesting thing that how to create one dimensional and two dimensional array without the help of new operator.
Example:
20 100 100 100 100 100 100 100 100 100
Now, let's discuss, how to create one dimensional array and two dimensional array using new operator.
Example:
20 20 20 100 100 100 100 100 100 100 100 100