Arrays in java
Arrays in java
Introduction:
An array in java is an indexed collection of fixed number of homogeneous data elements.
The main advantage of arrays is that multiple values can be represented with the same name so that readability of the code will be improved.
Also, the main disadvantage of arrays is:
Arrays in java is fixed in size that is once we created an array there is no chance of increasing or decreasing the size based on our requirement that is to use arrays it is mandatory to know the size in advance,which may not possible always.
We can resolve this problem by using collections.
Array declarations:
Single dimensional array declaration:
Example:
int[] arr; //recommended to use because name is clearly separated from the type
int []arr;
int arr[];
At the time of declaration we cannot specify the size otherwise we can get compile time error.
Example:
int[] arr; //valid
int[5] arr; //invalid
Two dimensional array declaration:
Example:
int[][] arr;
int [][]arr;
int arr[][]; All are valid. (6 ways)
int[] []arr;
int[] arr[];
int []arr[];
All are valid. (6 ways)
Three dimensional array declaration:
Example:
int[][][] arr;
int [][][]arr;
int arr[][][];
int[] [][]arr;
int[] arr[][];
int[] []arr[];
int[][] []arr;
int[][] arr[];
int []arr[][];
int [][]arr[];
Which of the following declarations are valid?
All are valid. (10 ways)
1. int[] c1,dl; //c-1,d-1 (valid)
2. int[] c2[], d2; //c-2,d-1 (valid)
3. int[] []c3,d3; //c-2,d-2 (valid)
4. int[] c,[]d; //C.E: expected (invalid)
Important Note:
If we want to specify the dimension before the variable that rule is valid only for the 1st variable.
Second variable on wards we cannot apply in the same declaration.
Example:
int[] []c,[]d;
Here, []d is invalid
[]c is valid
Array construction:
Every array in java is an object therefore array can created by using new operator.
Example:
int[] arr=new int[3];
We have to notice that for every array type corresponding classes are available but these classes are part of java language and not available to the programmer level.
Rule 1:
At the time of array creation it is mandatory to specify the size otherwise we can get compile time error.
Example:
int[] arr=new int[3];
int[] arr=new int[]; //C.E: array dimension missing
Rule 2:
In Java, it is legal or legitimate to have an array with size zero in java.
Example:
int[] arr=new int[0];
System.out.println(arr.length); //0
Rule 3:
If we are taking array size with -ve int value then we can get runtime exception saying NegativeArraySizeException.
Example:
int [] arr=new int[-3]; //R.E: NegativeArraySizeException
Rule 4:
The permitted data types to specify array size are int,char, short and byte. By mistake if we are using any other type we can get compile time error.
Example:
int[] arr=new int['a']; //(valid)
byte bt=10;
int [] arr=new int [bt]; // (valid)
short s1=20;
int[] arr=new int[s1]; // (valid)
int [] arr=new int [101]; //c.E:possible loss of precision// (invalid)
int[] arr=new int [10.5]; //C.E:possible loss of precision//(invalid)
Rule 5:
The maximum permitted array size in java is maximum value of int size [2147483647].
Example:
int[] arrl=new int[2147483647]: (valid)
int[] arr2=new int[2147483648]; //C.E:integer number too large: 2147483648 (invalid)
In the first case we might get RE : OutOfMemoryError.
Multi dimensional array creation:
In java multidimensional arrays can be implemented by using array of arrays approach but not matrix form.
The main advantage of using multidimensional arrays is to improve memory utilization.
Example 1:
int[][] arr=new int[2][];
arr[0]=new int[3];
arr[1]=new int[2];
Diagram:
Example 2:
int[][][] arr=new int[2][][];
arr[0]=new int[3][];
arr[0] [0]=new int [1];
arr[0] [1]=new int[2];
arr[0] [2]=new int[3];
arr[1]=new int[2] [2];
Diagram:
Which of the following declarations are valid?
int[] arr=new int[]; //C.E: array dimension missing (invalid)
int[][] arr=new int[3][4]; //(valid)
int[][] arr=new int[3][]; //(valid)
int[] arr=new int[][4]; //C.E:'1' expected (invalid)
int[][][] arr=new int[3][4][5]; //(valid)
int[][][] arr=new int[3][4][]; //(valid)
int[][][] arr=new int[3][][5]; //C.E:']' expected (invalid)
Array Initialization:
Whenever there is creation of an array then every element is initialized with default value automatically.
Example 1:
int[] arr=new int[3];
System.out.println(arr); //[I@3e25a5]
System.out.println(arr[0]); //0
Diagram:
Important Note:
When we try to print any object reference internally toString() method will be executed which is implemented by default to return the following.
classname@ hexadecimalstringrepresentationofhashcode.
Example 2:
int[][] arr=new int[2][3]; base size
System.out.println(arr) ; //I [[I@3e25a5
System.out.println(arr[0]); //[[I@19821f
System.out.println(arr[0][0]); //0
Diagram:
Example 3:
int[][] arr=new int[2][];
System.out.println(arr); // [[I@3e25a5
System.out.println(arr[0]); //null
System.out.println(arr[0][0]); //R.E:Nul1PointerException
Once array is created then all its elements by default initialized with default values,
If not satisfied with those default values then we can initialize with our customized values.
Example:
int[] arr=new int[4];
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50; //R.E:ArrayIndexOutofBoundsException: 4
arr[-4]=60; //R.E: ArrayIndexOuto£BoundsException: -4
Important Note:
If there is a try to access array element with out of range index we can get Runtime Exception saying ArrayIndexOutOfBoundsException.
Now we have to look into,How to Declare, construct and initialize an array in a single line?
We can do declaration, construction and initialization of an array in a single line.
Example:
int[] arr;
arr=new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30;
int[] arr={10,20,30};
char[] ch=('a', 'e', 'i', 'o', 'u'}; (valid)
String[] s1=("I", "LOVE", "YOU","JAVA"}; (valid)
Also,we can perform this short cut even for multi dimensional arrays also.
Example:
int[][] arr={{10, 20,30), { 40,50}};
Example:
int[][][] arr={{{10,20,30}, {40,50}}, {{60},{70,80}, {90,100,110}}};
System.out.println(arr[0][1][1]); //50 (valid)
System.out.println(arr[1][0][2]); //R.E:ArrayIndexOutOfBoundsException:
System.out.println(arr[1][2][1]); //100 (valid)
System.out.println(arr[1][2][2]); //110 (valid)
System.out.println(arr[2][1][0]); //R.E:ArrayIndexOutofBoundsException;
System.out.println(arr[1][1][1]); //80 (valid)
If we want to use this short cut then it is mandatory that we should perform declaration,
construction and initialization in a single line .
If we are trying to divide into multiple lines then we can get compile time error.
Example:
int[] arr={10,20,30};
int[] arr;
arr=new int[3];
arr={10,20,30}; //C.E: illegal start of expression
length Vs length():
length:
1. length is the final variable applicable only for arrays.
2. length represents the size of the array.
Example:
int [] arr=new int[3];
System.out.println(arr.length ()); //C.E: cannot find Bymbol
System.out.println(arr.length) : //3
length() method:
1. length() is a final method applicable for String objects.
2. length() returns the number of characters present in the String.
Example:
String arr="bhaskar",
System.out.println(arr.length); //C.E:cannot find aua
System.out.println(arr.length()); // 7
In multidimensional arrays, length variable just represents base size but not total size.
Example:
int [][] arr=new int[6][3];
System.out.println(arr.length); //6
System.out.println(a[0].length); //3
length variable valid only for arrays where as length()method is valid for
String objects.
There is no direct way to find total size of multi dimensional array but indirectly we can
find as follows
arr[0].length +arr[1].length + arr[2].length + arr[3].length + so on..........
Anonymous Arrays:
A array which is created without name such type of nameless arrays are called as anonymous arrays.
The main objective of anonymous arrays is "just for instant use".
We can create anonymous array as follows.
new int[](10,20,30,40); (valid)
new int[][]{{10,20},130,40}}; (valid)
At the time of anonymous array creation we can't specify the size otherwise we can get compile time error.
Example:
new int[3]{10,20, 30,40}; //C.E:';' expected (invalid)
new int[]{10,20,30, 40}; //(valid)
Based on our programming requirement we can give the name for anonymous array then it is no longer anonymous.
Example:
int[] a=new int[]{10,20,30, 40}; //(valid)
"Never Forget Why you started."
Post a Comment