Array
- Array is a collection of similar data type of elements.
- They are stored in continuous memory space.
- Array is treated as Object.
- Array is fixed size & its mandatory to define size while creating an Array.
- [] brackets used to represent Array in Java.
- We can access values stored in Array using their index. Array index starts from Zero.
Defining Array
There are two ways to define an Array
Method 1
int a[] = new int[2];
a[0]=10;
a[1]=20;
Method 2
int a[] = {33,3,4,5};
Iterating over an Array
To iterate over an Array, we can either use for loop or enhanced for loop
Using For Loop
int[] array = {1, 2, 3, 4, 5};
for(int i=0;i<array.length;i++) {
System.out.println(array[i]);
}
Using Enhanced For Loop
int[] array = {1, 2, 3, 4, 5};
for(int a: array) {
System.out.println(a);
}
Default values
When we create an Array, default values are assigned to all indexes
if its an int[]
, every index will have value 0
if its a double[]
, every index will have value 0.0
if its an Object array, say Student[]
, every index will have value null
Array Default Values
double[] arr = new double[2];
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// Output
// 0.0
// 0.0
ArrayIndexOutOfBoundsException
If we try to access index which is outside of Array size, we will get ArrayIndexOutOfBoundsException
int[] array = {1, 2, 3, 4, 5};
System.out.println(array[7]);
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
// Index 7 out of bounds for length 5