JavaIntellectualTricks

Arrays

  1. Introduction
  2. Array Declaration
  3. Array Creation
  4. Array Initialization
  5. Array Declaration, creation and initialization in a single line
  6. length vs length()
  7. Anonymous Arrays
  8. Array Element Assignments
  9. Array variable Assignments
Introduction:-

  • An array is an indexed collection of fixed number of homogeneous data elements.
The main advantage of arrays is , we can represent huge number of values by using single variable. So that readability of the code will be improved, but the main disadvantage of the arrays is fixed in size i.e once we creates an array there is no chance of increasing or decreasing in the size based on the requirement.
Hence to use arrays concept, compulsory we should know the size in advance , which may not possible always.
Array Declaration:-

One Dimensional Array Declaration:-
int[] x ; //valid and recommended because name is clearly separated from type.
int []x; //valid but not recommended.
int x[]; //valid but not recommended.

At the time of declaration we can't specify the size , otherwise we ll get compile time error.
Example: int[6] x; //Invalid

Two Dimensional Array Declaration:-
int[][] x ; //valid and recommended because name is clearly separated from type.
int [][]x; //valid but not recommended.
int x[][]; //valid but not recommended.
int[] []x; //valid but not recommended.
int[] x[]; //valid but not recommended.
int []x[]; //valid but not recommended.

Q.Which of the followings are valid?
  1. int[] a,b; // valid ,a's dimension=1 & b's dimension=1
  2. int[] a[],b; //valid ,a's dimension=2 & b's dimension=1
  3. int[] a[],b[]; //valid ,a's dimension=2 & b's dimension=2
  4. int[] []a,b; //valid, a's dimension=2 & b's dimension=2
  5. int[] []a,b[]; //valid, a's dimension=2 & b's dimension=3
  6. int[] []a,[]b; //Invalid

  • If we want to specify dimension before the variable, that facility is applicable only for first variable in a declaration. If we are trying to apply for remaining variables ,we ll get compile time error. Ex: int[] []a (valid), []b (Invalid), []c (Invalid);
Three Dimensional Array Declaration:-
int [][][]a; //valid
int [][][]a; //valid
int a[][][]; //valid
int[] [][]a; //valid
int[] a[][]; //valid
int[] []a[]; //valid
int[][] []a; //valid
int[][] a[]; //valid
int [][]a[]; //valid
int []a[][]; //valid

Array Creation:-
Every array in java is an object only,hence we can create arrays by using 'new' operator.
Example:
int[] a=new int[3];
For every array type, corresponding classes are available and these classses are part of java language and not available to the programmer level.

int[] a=new int[3];
System.out.println(a.getClass().getname()); // o/p: [I
ArrayType
Corresponding Class Name
int[]
[I
int[][]
[[I
double[]
[D
short[]
[S
byte[]
[B
boolean[]
[Z
Points:
  1. At the time of array creation , compulsory we should specify the size, Otherwise we ll get compile time error.
    Example:- int[] x=new int[]; // Invalid
            int[] x=new int[6]; //valid
  1. It is legal to have an array with size zero in java.
    Example: int[] x=new int[0]; //valid
  2. If we are trying to specify array size with some negative int value, then we ll get Run time Exception saying NegativeArraySizeException.
    Example: int[] x=new int[-6]; //No Compile Time Error
  3. To specify array size , the allowed data types are byte,short,char,int. If we are trying to specify any other type, then we ll get compile time error.
    Example: int[] x=new int[10]; // valid
    int[] x=new int['a']; //valid
    byte b=20;
    int[] x=new int[b]; //valid
    short s=10;
    int[] x=new int[10l]; //Invalid C.E possible loss of precession, found: long, required: int
  4. The maximum allowed array size in java is 2147483647, which is the maximum value of int data type.
    Example: (i) int[] x=new int[2147483647]; //valid
             (ii) int[] x=new int[2147483648]; // C.E. Integer Number too large
Even in the (i) case we may get a Run time Exception if sufficient heap memory is not available.

Two Dimensional Array Creation:-
In java 2 D array is not implemented by using matrix style. Sun people followed array of arrays approach for multi dimensional array creation.
The main advantage of this approach is memory utilization will be improved.
Example:-
Student No
Math
Physics
Chemistry
Bio
1
45
12
23
12
2
56
64
Not appeared
Not appeared
3
85
Not appeared
Not appeared
Not appeared
Here “Not appeared” memory locations are wasted, so SUN people followed array of arrays approach i.e.
Here memory is optimized.
Example-1:
int[][] x=new int [2][];
x[0]=new int[2];
x[1]=new int[3];
                                                                        (Example-1)

Example-2:
int[][][] x=new int [2][][];
x[0]=new int[3][];
x[0][0]=new int[1];
x[0][1]=new int[2];
x[0][2]=new int[3];
x[1]=new int[2][2];
x[1][0]=new int[2];
x[01[1]=new int[2];

                                                                          (Example-2)

Q.Which of the following array declarations are valid ?

1. int[] a= new int[]; //Invalid, at least base size must be specified
2. int[] a= new int[3]; //valid
3. int[][] a= new int[][]; //Invalid, at least base size must be specified
4. int[][] a= new int[3][]; //valid
5. int[][] a= new int[][4]; //Invalid, base size must be specified
6. int[][] a= new int[3][4]; //valid
7. int[][][] a= new int[3][4][5]; //valid
8. int[][][] a= new int[3][4][]; //valid
9. int[][][] a= new int[3][][5]; //Invalid; without 2nd dimension we can't assign 3rd dimension
10.int[][][] a= new int[][4][5]; //Invalid; without 1st dimension we can't assign 2nd and 3rd dimension

Array Initialization:
Once we creates an array, every element by default initialized with default values.
Example-1:
Int[] x=new int[3];
System.out.println(x); // [I@8d00ce
System.out.println(x[0]); //0
Example-2:
Int[][] x=new int[2][3];
System.out.println(x); // [[I@8d00ce
System.out.println(x[0]); // [I@7f00de
System.out.println(x[0])[0]; //0
Example-3:
Int[][] x=new int[2][];
System.out.println(x); // [[I@8d00ce
System.out.println(x[0]); // null
System.out.println(x[0])[0]; //NullPointerException

Note: If we are trying to perform any operation on null, then we ll get run time exception saying “NullPointerException”.

Once we creates an array, every array element by default initialized with default values.
If we are not satisfied with default values,then we can override these values with our customized values.
int[] x=new int[6];
x[0]=10;
x[1]=20;
x[2]=30;
x[3]=40;
x[4]=50;
x[5]=60;
x[6]=70; // ArrayIndexOutOfBoundsException
x[-6]=80; // ArrayIndexOutOfBoundsException
x[2.5]=90; // Compilation Error, Possible loss of precission, found :double, required :int

Note: If we are trying to access array element with out of range index (either +ve or -ve int value), then we ll get runtime exception saying “ArrayIndexOutOfBoundsException”.

 Array Declaration,Creation and Initialization in a single line:-

we can declare, create and initialize an array in a single line(shortcut representation)
Example:-
int [] x;
x=new int[3];
x[0]=10;
x[1]=20;
x[2]=30;
 //Alternate way
int [] x={10,20,30};
char[] ch={'a','e','i','o','u'};
String [] s={"A","AA","AAA"};
We can use this shortcut for multidimensional arrays also.

Example 1:
int[][] x={{10,20}{30,40,50}};
see the below figure for memory representation.
(Example-1)
Example 2:
int [][][] x={{{10,20,30},{40,50,60}},{{70,80},{90,100,110}}};
                                                                   (Example-2)
System.out.println(x[0][1][2]);//60
System.out.println(x[1][0][1]);//80
System.out.println(x[2][0][0]);//ArrayIndexOutsOfBoundsException
System.out.println(x[1][2][0]);//ArrayIndexOutsOfBoundsException
System.out.println(x[1][1][1]);//100
System.out.println(x[2][1][0]);//ArrayIndexOutsOfBoundsException
 case:1
 If we want to use this shortcut compulsory we should perform all activities in a single line. If we are trying to divide into m multiple lines , then we will get compile time error.
 Example 1:
int x=10; == int x; x=10;
int [] x={10,20,30}; == int [] x;(correct) x={10,20,30};(illegal start of expression)

 length vs length( ):-

length:
length is a final variable applicable for arrays.
length variable represents the size of the array.
Example:
int [] x=new int[6];
s.o.p(x.length());//C.E. can't find symbol method length() location class int[]
s.o.p(x.length);//6
length( ):
length( ) is a final method applicable for String objects.
length( ) returns number of characters present in the String.
 Example:
 String s="purna";
s.o.p(s.length);//can't find symbol variable length location class java.lang.String
s.o.p(s.length());//5

Note:length variable applicable for arrays but not for String objects where as length() applicable for String objects but not for arrays.
 String [] s={"A","AA","AAA"};
s.o.p(s.length); // correct
s.o.p(s.length()); //C.E can't find symbol ,symbol: variable length(), location: class String[]
s.o.p(s[0].length); //C.E can't find symbol ,variable length, location: class- java.lang.String
s.o.p(s[0].length()); //correct
Example:
int [][] x=new int [6][3];
System.out.println(x.length);//6
System.out.println(x[0].length);//3
Note: In multi dimensional length variable represents only base size but not total size.
There is no direct to way to find out total length of multi dimensional array but indirectly we can find as follows:
x[0].length+x[1].length+x[2].length+...........

Anonymous Array:
Sometimes we can declare an array without name, such type of name less arrays are called anonymous arrays.
The main purpose of anonymous arrays is just for instant use(one time usage).
Declaration:
we can create anonymous array as follows: new int[]{10,20,30,40}
1.while creating anonymous arrays we can't specify the size, otherwise we will get compile time error.
Example:
new int[4]{10,20,30,40} //invalid
new int[]{10,20,30,40} //valid

class Test{
public static void main(String [] args){
sum(new int[]{10,20,30,40});
}

public static void sum(int [] x){
int total=0;
for(int x1: x){
total=total+x1;
}
System.out.println(“The sum is”+ total);
}
}
In the above example just to call sum(), we require an array, but after completing sum() method call we are not using that array anymore. Hence for this one requirement anonymous array is the best choice.
2. We can create multi dimensional anonymous arrays also.
new int []{{10,20},{30,40,50}}
3.Based on our requirement we can give the name for anonymous array, then it is no longer anonymous.
new int[{10,20,30}] //anonymous
Int [] x= new int[{10,20,30}]; //not anonymous

 Array element assignments:-
Case 1:
In the case of primitive type arrays as array elements, we can provide any type,which can be implicitly promoted to declared type.
Example:
int [] x= new int[5];
x[0]=10;
x[1]='a';
byte b=20;
x[2]=b;
short s=30;
x[3] =s;
x[4]=10l; //C.E. Possible loss of precision found long required :int
In the case of float type arrays, the allowed data types are byte,short,int,long,char,float.
Case 2:
In the case of Object type arrays as array elements ,we can provide either declared type objects or it's child class objects.
Example 1:
Object [] a=new Object[10];
a[0]=new Object();
a[1]=new String(“purna”);
a[2]=new Integer(10);
Example 2:
Number [] n=new Number[10];
n[0]=new Integer(10);
n[1]=new Double(10.5);
n[2]=new String(“purna”); // C.E. Incompatible types: found java.lang.String, required: java.lang.Number
Case 3:
For interface type arrays as array elements,it's implementation class objects are allowed.
Runnable [] r = new Runnable[10];
r[0]=new Thread(); //Here: Class Thread implements Runnable
r[1]=new String(“purna”); //C.E. Incompatible type found: java.lang.String required java.lang.Runnable.
Array Type Allowed element type
Primitive Arrays Any type which can be implicitly promoted to declared type.
Object type Arrays Either declared type or its child class objects
Abstract class type Arrays It's child class objects
Interface type Array It's implementation class objects
Array variable Assignments:

Case 1:
Element level promotions are not applicable at array level.
char element can be promoted to int type, where as char [] can't be promoted to int[].
Example:
int [] a={10,20,30,40};
char [] ch={'a','b','c','d'};
int [] b=a; //valid
int [] c=ch; //invalid C.E Incompatible type found char[] required: int[]

Q.Which of the following promotions will be performed automatically?
1. char --> int //valid
2. char[] -->int[] //invalid
3. int --> double //valid
4. int[] --> double[] //invalid
5. float --> int //invalid
6. float[] --> int[] //invalid
7. String --> Object //valid
8.String[] --> Object[] //valid

Note: But in the case of object type array, the child class type array can be promoted to parent class type array.
String [] s={“A”,”B”,”C”};
Object [] a=s; //valid

Case 2:
Whenever we are assigning one array to another array, internal elements won't be coppied, just reference variables will be reassigned.
int[] a={10,20,30,40,50};
int[] b={60,70,80};
  1. a=b; //valid
  2. b=a; //valid
Case 3:
Whenever we are assigning one array to another array, the dimensions must be matched. For example in the place of one dimensional int array we should provide one dimensional int array only.
If we are trying to provide any other dimension, then we will get compile time error.

int[][] a= new int[3][];
a[0]= new int[4][3]; // C.E Incompatible type found int[][], required int[]
a[0]=10; // C.E Incompatible type found int, required int[]
a[0]=new int[2]; //valid
Note: Whenever we are assigning one array to another array, both dimensions and type must be matched but sizes are not required to match.
Example 1:
class Test{
public static void main(String [] args){
for(int i=0;i<args.length;i++){

System.out.println(args[i]);
}
}
}
java Test A B C // O/P- A B C ArrayIndexOutOfBoundsException
java Test A B // O/P- A B ArrayIndexOutOfBoundsException
java Test // O/P- ArrayIndexOutOfBoundsException

Example 2:
class Test{
public static void main(String [] args){
String [] argh ={“A”,”B”,”C”};
args=argh;
for(String s:args ){
System.out.println(s);
}
}
}
java Test A B C // O/P- X Y Z
java Test A B // O/P- X Y Z
java Test // O/P- X Y Z
Example 3:
int[][] a= new int[4][3]; // Here 5 objects are created
a[0]= new int[4]; // Here 1 object is created
a[1]= new int[2]; // Here 1 object is created
a= new int[3][2]; // Here 4 objects are created
Total How many Objects are created here ? Ans- 11
Total How many Objects are eligible for garbage collected ? Ans- 7

1 comment:

  1. Very innovative and interesting information you shared. I think no other popular websites share this type of information in this kind of collective manner.
    Thank you for sharing

    ReplyDelete