Arrays Summary
- Array is an object in Java.
- You canβt specify the size of an array at the time of declaration.
int a[];// VALID
int a[1];// INVALID
- Array size is mandatory while constructing an array object.
int a[]=new int[3];// VALID
int a[]=new int[];// INVALID
- Size of an array must be int compatible type (byte, char, short, int).
- Size of an array must be in the range of 0 to 2147483647.
- Size of an array can be provided using a variable.
- If you specify a negative value as array size β β‘ java.lang.NegativeArraySizeException (runtime)
- If sufficient memory is not available β β‘ java.lang.OutOfMemoryError (runtime)
- Elements of an array can be accessed using index representation.
- Index range is from 0 to size-1.
- If array size is 0 β
- No elements allocated
- You cannot access any index
- Accessing an invalid index β β‘ java.lang.ArrayIndexOutOfBoundsException
- Accessing array using a null reference β β‘ java.lang.NullPointerException
- Arrays are static in nature β once created, size cannot be changed.
- Array reference variable can be modified.
- If array reference is declared as
finalβ
- Reference cannot be changed
- But elements can be modified
- Since array is an object, reference can be stored in
Objecttype
int arr[]=new int[5];
Object obj=arr;// VALID
- With Object reference, index representation canβt be used
obj[0];// INVALID
- You can assign one array into another if both are of same type
int arr1[]=new int[2];
int arr2[]=arr1;// VALID
π‘ Quick Understandingβ
- Array = object + fixed size
- Index always starts from 0
- Most common errors:
- NullPointerException
- ArrayIndexOutOfBoundsException
- NegativeArraySizeException
Arrays β Additional Points
20)β
You canβt assign one array into another array when both arrays are of different types
byte arr1[]=new byte[2];
int arr2[]=arr1;// INVALID
21)β
The class for the array will be generated at runtime based on the dimension and data type.
22)β
When you assign one array to another, the array address is copied, so both references point to the same array object.
23)β
If you modify elements using one reference, the changes will be reflected in the other reference as well.
24)β
You canβt use the + operator with an array reference variable
int arr[]=new int[3];
(arr+1);// INVALID
25)β
When constructing a multi-dimensional array, the first dimension is mandatory, and other dimensions can be ignored.
Example (a)β
int arr[][]=new int[3][2];
β Creates 3 arrays, each of size 2
Example (b)β
int arr[][]=new int[3][];
arr[0]=new int[2];
arr[1]=new int[3];
arr[2]=new int[4];
β Creates 3 arrays with sizes:
- arr[0] β 2 elements
- arr[1] β 3 elements
- arr[2] β 4 elements
π‘ Quick Understandingβ
- Arrays of different types cannot be assigned
- Array assignment = reference copy (not data copy)
- Changes reflect across references β
- Multi-dimensional arrays β jagged arrays supported