An array can be primitive or reference type. Storage in the heap area begins with the index of the array starting from zero to size -1.
Advantage Array
Code Optimization: This code optimizes, we can easily retrieve or sort the data
Random access: We can get any data located in any index position.
Disadvantage Array
Size range: We can store only certain size elements in the array. It does not grow at the runtime. In order to solve this problem, the archive framework is used in Java.
Array Declaration
Syntax - datatype[] identifier; or
datatype identifier[];
Example -
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.
Initialization of Array
The new operator is used to start an array.
int[] arr = new int[10]; //this creates an empty array named arr of integer type whose size is 10.
or
int[] arr = {10,20,30,40,50}; //this creates an array named arr whose elements are given.
foreach or enhanced for loop
In JSCE 5, there is a special type of introduction to the loop called Focal Loop to reach the elements of Array. Using the forex loop, you can use the full array without using the array index. Let us see an example of foreach loop.
class Test
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr)
{
System.out.println(x);
}
}
}
Multidimensional array
A multi-dimensional array is similar to a one-dimensional array that can have multiple rows and more than one column, which can be contrary to the only dimensional array, which can only have a full line or a full column.
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Initialization of Array
int[ ][ ] arr = new int[10][10]; //10 by 10 is the size of array.
or
int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
// 3 by 5 is the size of the array.
Jagged Array
It means to be uneven edge or surface. In java, a jagged array means that there is a multi-dimensional array that has unequal lines of rows.
int[ ][ ] arr = new int[3][ ]; //there will be 10 arrays whose size is variable
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[5];
0 comments:
Post a Comment