Arrays are used to store homogenous elements/values (of same data type),
can access the elements by the indexes.
Let's see some of the implementation of the array.
One dimentional array:
dataType[] varName //declaring array variable
varName = new dataTyp[Size of array]
e.g: int a[]; or int[] a;
a = new int[2];
So we have 2 ways to declare and assign values:
Like this we can have multi dimentional array.
Limitations of arrays:
To overcome this limitations, we normally use collections framework (List / Set / hashMap),
but it is highly recomended to use Arrays if we already know the size, we will be discussing this in
collections framework topic.
can access the elements by the indexes.
One dimentional array:
dataType[] varName //declaring array variable
varName = new dataTyp[Size of array]
e.g: int a[]; or int[] a;
a = new int[2];
/*String[] names = new String[3]; //A total of 3 elements can hold *names[0] = "sun"; *names[1] = "moon"; *names[2] = "mars"; */ //or directly we can declare and assign values String[] names = {"sun", "moon", "mars"}; //index starts from 0 system.out.println("No of elements:"+names.length); //0 to name.length-1 for(int i=0;i<names.length;i++) { system.out.println(names[i]); //prints each element of array } //Another type of for loop for(String name: names) { system.out.println(name); }
So we have 2 ways to declare and assign values:
- Declare the array variable and specify the size, and then assign values to each index
- Declare and assign values then n there, no need to specify the size.
Let's see different ways of declaring, assigning and accessing 2 dimensional array in java -
int arr2d[][] = new int[2][3]; //or, we can declare each row size /*int arr2d[][] = new int[2][]; //atleast u must specify the size of 1st dimension, Row Size *int arr2d[0] = new int[3]; *int arr2d[1] = new int[3]; *int arr2d[2] = new int[3]; */ //Assign values arr2d[0][0] = 1; arr2d[0][1] = 2; arr2d[0][2] = 3; arr2d[1][0] = 4; arr2d[1][1] = 5; arr2d[1][2] = 6; //or, declare and assign values, no need to specify size int[][] arr2d = {{1,2,3},{4,5,6}}; //system.out.println("Rows:"+arr2d.length); //Output: Rows:2 //system.out.println("Columns on 1st Row:"arr2d[0].length); //Output:Columns on 1st Row:3 //Get the 2d array values using 2 loops for (int i = 0; i < arr2d.length; i++) { for (int j = 0; j < arr2d[i].length; j++) { system.out.print(arr2d[i][j]); } system.out.println(); //this line, just for formatting output }
Like this we can have multi dimentional array.
Limitations of arrays:
- Arrays can have only homogenius elements (same data type).
- Array size is fixed (once we declared the size, we can not alter it)
- Not all ready made methods are not present for arrays
To overcome this limitations, we normally use collections framework (List / Set / hashMap),
but it is highly recomended to use Arrays if we already know the size, we will be discussing this in
collections framework topic.
No comments:
Post a Comment