Arrays In Java
Arrays
● An array is a like-typed variables that are referred to by a common name
● Array of any type can be created and can have one or more dimensions.
● Array always starts from the index 0 (zero).
● Internally arrays are like objects.
● [Link] gives size of the array (not the number of elements present
in the array)
Arrays : One Dimensional
● type var-name[ ] = new type [size]
○ Ex. int arr[ ] = new int [5];
● Arrays can be initialized when it is declared.
○ Ex. int arr[ ] = {10,20,30,40,50}
● If we don’t assign values, array elements contain default values.
● Java shows run time error if any attempt is made to acces the value outside
the range of the array.
Arrays : Two Dimensional
● type var-name[ ] [ ] = new type [rowsize] [colsize]
○ Ex. int arr[ ] [ ] = new int [3] [5];
● Arrays can be initialized when it is declared.
○ Ex. int arr[ ] [ ] = {
{1,2,3,4,5},
{5,6,7,8,9},
{10,11,12,13,14}
};
● Java shows run time error if any attempt is made to acces the value outside
the range of the array.
Arrays : Two Dimensional
int nums [ ] [ ] = new int [5] [4]
nums
0 1 2 3
0 2 8 1 6
1 1 6 5 3
2 3 2 6 4
3 2 9 7 2
4 9 3 1 5
Arrays : Two Dimensional
Arrays : Alternative Array Declaration Syntax
1. int a [ ] = new int [5];
int [ ] a = new int [5];
2. int arr[ ] [ ] = new int [5][4];
Int [ ] [ ] arr = new int [5][4];
3. int [ ] nums1, nums2, nums3; // Creates three array variables or references
4. int nums1[ ], nums2 [ ], nums3 [ ]; // Creates three array references
Arrays : Jagged Arrays
● A jagged array in an array that contains a group of arrays within it. It is also
called ‘irregular multidimensional arrays’.
● Jagged arrays are useful when dealing with group of arrays of different sizes.
● int x [ ] [ ] = new int [2] [ ]
x [0] = new int [2]; // memory for first array
x [1] = new int[3]; // memory for second array
Arrays : Jagged Arrays
int numArr [ ] [ ] = {
{1,2,3},
{4,5,6,7},
{8,9}
};