What is array? How arrays in java are different? Explain different types of arrays with example.
Array
An array is a collection of similar type of elements which has contiguous memory location.
arrays in java are different are described below:-
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on the 1st index, and so on.
Types of Array in java
There are two types of array.
- Single Dimensional Array
- Multidimensional Array
2. Multidimensional array in java
In such cases, data is stored in row and column-based index which is also known as matrix form.
Syntax to Declare Multidimensional Array in java
dataType[][] ar;or
dataType [] []ar;or
dataType ar[][];or
dataType []ar[];
Example to instantiate Multidimensional Array in java
int[][] ar=new int [3] [3];//3 row and 3 column
Example of Multidimensional java array
Let's see the simple example to Declare instantiate, initialize and print the two-dimensional array.
import java.util.*;
class TestArray
{
public static void main(String args[])
{
int a[][]=new int[3][3];//declaration and instantiation
Scanner sc=new Scanner(System.in);
System.out.printIn("Enter elements");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j]=sc.nextint();
System.out.printIn("------Enter Elements Are----------\n");
for(int i=0;i<3;i++) ;
{
for(int j=0;j<3;j++) ·
{
System.out.print(a[i][j]+" "); .. .
}
System.out.printIn();
}
}
}
Comments
Post a Comment