Arrays in Java

An array is a data structure that represents an index collection of fixed no of homogeneous data elements. The main advantage of arrays is we can represent a group of values with single name hence readability of the code will be improved. The main limitation of arrays is they are fixed in size. i.e once we constructed an array there is no chance of increasing or decreasing bases on our
requirement hence with respect to memory arrays shows worst performance we can overcome this problem by using collections.

Array Declaration

The following are the ways to declare an array.

1) int [] a;
2) int a[];
3) int [] a;

The first one is recommended to use because the type is clearly separated from the name. At the first time of declarations we are not allowed to specify the size. Violation leads to C.E.

int[] a;  //Invalid
int[6] a; //Valid

Declaring Multidimensional Arrays

The following are the valid declarations for multidimensional arrays.

int[][] a;
int a[][];
int [][]a;
int[] a[];
int[] []a;

we can specify the dimension before name of variable also, but this facility is available only for the first variable.

int[] a[],b[]; //Valid 
int[] []a,[]b; //Invalid

Which of the following declarations are valid?

i. int[2][3] a;
ii. int[] a,b;
iii. int[] a[],b[];
iv. int []a,[]b;
v. int []a,b[];

Ans- 2,3,5

Construction of Arrays

Single Dimension : Arrays are internally implemented as object hence by using new operator we can construct an array. Compulsory at the time of construction we should specify the size otherwise compile time error.


int[] a = new int[10]; //Valid
int[] a = new int[];  //Invalid

It is legal to have an error with size 0 there is no C.E or R.E

int[] a = new int[0];

If we are specifying array size with some –ve integer

int[] a = new int[-10];

we will get R.E saying NegativeArraySizeException. The only allowed Data type to allow the size are byte, short, char, int. if we are using any other datatype we will get a C.E.

int[] a = new int[10];
int[] a1 = new int[10l];
int[] a = new int[10l];  
// C.E possible loss of precision found: long required: int
int[] a = new int[10.5];// C.E
int[] a = new int[true];  
// C.E Incompatible types found : boolean required:int.

The maximum allowed Array Size in java is 2147483648.

Multi Dimension: In java multidimensional arrays are implemented as single dimension arrays. This approach improves performance with respect to memory.

int[][] a = new int[3][2];

int[][] a = new int[4][]
a[0] = new int[1];
a[1] = new int[2];
a[2] = new int[4];
a[3] = new int[3];

Which of the following Array declarations are valid?

int [][] a = new int[3][4]; 
int [][] a = new int[3][]; 
int [][] a = new int[][4]; 
int [][] a = new int[][]; 
int [][][] a = new int[3][4][]; 
int [][][] a = new int[3][][5]; 

Ans- 1,2,5

Initialization of arrays

Once we created an array all it’s elements initialized with default values.


int[] a = new int[3];
System.out.println(a[0]); // O/P: 0
System.out.println(a);     // O/P: [I@10b62c9
int[][] a = new int[3][2];
System.out.println(a);     // [I@10b62c9
System.out.println(a[0]); // [[I@82ba41
System.out.println(a[0][0]); // 0
int[][] a = new int[3][];
System.out.println(a);     // [I@10b62c9
System.out.println(a[0]); // null
System.out.println(a[0][0]); // NullPointerException

Once we created an array all it’s elements are initialized with default values.
If we are providing any explicit initialization then default values will be overridden with our provided values.


int[] a = new int[3];
a[0] = 10;
a[1] = 20;
System.out.println(a[0] + "---" + a[1] + "---" + a[2]);
a[10] = 100; // R.E: ArrayIndexOutOfBoundsException.
a[-10] = 100; // R.E: ArrayIndexOutOfBoundsException.
a[10.5] = 100; // C.E: PossibleLossOfPrecision found : double required : int

when ever we are trying to access an array with int index which is not in valid range then we will get runtime exception saying “ArrayIndexOutOfBoundsException”. But there is no C.E. If we are trying to access an array index with the following datatype we will get C.E. float, double, long, boolean.

Declaration Construction and Initialization in a single line

int []a;
a = new int[3];
a[0] = 10;
a[1] = 20;
a[2] = 30;

All these statements we can replace with a single line as follows.

int[] a = {10,20,30};
String[] s = {“Chiru”,”Allu”,”Ram”,”Akil”}

If we want to use the above shortcut technique compulsory we should perform declaration, construction initialization in a single line only. If we are dividing into 2 lines we will get C.E


int[] a;
a = {10,20,30,40}; //C.E: illegal start of expression.
int[][] a = {{10,20},{30,40,50}};
int[][][] a = {{{10,20},{30,40}},{{50,60},{70,80}}};

length Vs length();

1) It is the final variable applicable for array objects.
2) It represents the size of the array.
int [] a = new int[5];
System.out.println(a.length()); // C.E
System.out.println(a.length); // 6

1) It is the final method applicable only for String Objects.
2) It represents the no of characters present in the String.
String s = "raju";
System.out.println(s.length); // C.E
System.out.println(s.length()); // 4

In the case of Multidimensional array length variable always represent base size but not total no of elements.
int[][] a = new [3][2];

There is no variable which represents the total no of elements present in multidimensional arrays.

Anonymous Arrays

Some times we can declare an array with out name also such type of arrays are called anonymous arrays. The main objective of anonymous arrays is just for temporary usage. We can create an anonymous arrays as follows.

new int[] {10,20,30} 

class Test

    public static void main(String arg[]) 
        System.out.println(sum(new int[]{10, 20, 30, 40}));

    public static int sum(int[] a)

        int total = 0;
        for (int i = 0; i < a.length; i++) 
            total = total + a[i];
        return total;

Array Element Assignments

In the case of primitive arrays as array element any datatype is allowed which can be implicitly promoted to the declared type.

int [] a = new int[10];

in this case the following datatypes are allowed as array elements.
byte, short, int, char.

a[0] = 10;
a[1] = 'a';
byte b = 20;
a[2] = b;
a[3] = 10.5; // possible loss of precision. found : double required: int

in the case of object arrays as array elements we can provide either declared type object or it’s child class objects.

Number[] n = new Number[6];
n[0] = new Integer(10); //Valid
n[1] = new Long(10l); //Valid
n[2] = new String("raju"); //Invalid

If we declare an array of interface type we are allowed to provide it’s implementation class object as elements.

Runnable[] = new Runnable[]
r[0] = new Thread();

Array Variable Assignments

A char element can be promoted as the int element but a char array can’t be prompted to int array.

int [] a = new int[6];
int [] b = a;
char[] ch = {'a','b','c'};
int [] c = ch; // Incompatible types found : char[] required:int[]

when ever we are assigning one array to another array compiler will check only the types instead ofsizes

int[] a = {10,20,30,40};
int[] b = {60,70};
See the following example.
int [][] a = new int[3][];
a[0] = new int[4];
a[1] = new int[4][5]; 
// Incompatible types found: int[][] required: int[]
a[2] = 10; // Incompatible types found: int required: int[]

No comments:

Post a Comment