An array is a group of variable of same data type. Each element in array is assigned a unique number to identify it uniquely. This is called subscript or index. The index starts with 0.
In java an array is created in 2 steps:-
In java an array is created in 2 steps:-
Declaring array variable:-
int arr[ ];
int [ ]arr;
These statements declare an array variable that will refer to an array that we have yet to define. No memory is allocated at this point.
Defining the array:-
arr = new int[5];
This statement creates an array of size 5 of type integer and reference to array is assigned to variable arr.
int arr[ ]; // same as int *arr; in c++
arr = new int[5]; // same as arr = new int[5];
In java when array is created all array elements are initialised to their default value automatically.
integer default value = 0
floating default value = 0.0
boolean default value = false
character default value = '\0' //null
In java each array has a length variable associated with it that returns number of elements in the array.
int arr[ ] = new int[5];
System.out.print(arr.length);
This will print the array size which is 5 here.
Array index:-
We can use any arithmetic expression on an array index. If we specify an invalid index it will throw an exception at run time.
Array Index Out Of Bound Exception
Array Index Out Of Bound Exception
A long type expression is not allowed as an array index. It is compile time error.
Example:
int a[ ]= {25, 35, 45}; //valid
int b[ ]= new int[]{25, 35, 45}; //valid
int c[ ]= new int[3]{25, 35, 45}; //not valid as when we defined array size as 3 it is already initialised with 0.
int d[ ]= {10,20,30}; //valid
int e[ ]= d; //valid as we know int e[ ] is same as int *e in c or c++ which is a pointer so it can point to any other memory address already existing.
No comments:
Post a Comment