Pages

Friday, February 10, 2017

Anonymous Array in Java

Anonymous Array in Java


If we are creating an array object then it will allocate memory and default value i.e zero is been set by the JVM in the allocated memory.

If we want to store the value at the time of declaring the array reference then we have the following statement,

< data_type >  < var_name > [  ]  =  {< value1 > , < value2 >,< value3 >.....} ;

int  value [ ] =  {  10, 20, 30 } ; // Valid statement 

int  value [ ] =  {  10, 20 ,30,  , } ; // Invalid statement 

int  value [ ] ;
value =  {  10, 20 ,30 } ; // Invalid statement it should be in one line .


 Anonymous Array 

Now if we have a requirement to assign the data at the time of creating the array object then we have the following statement and this is also known as Anonymous Array .

int  value [ ] =  new int[ ] {  10, 20, 30 } ; 

We can also assign one reference to another reference variable. Like this,

int  tmp [ ] ;
tmp = new int [ ] { 10,20,30 } ;

Note : We should not specify any size while creating the anonymous array . 

Important points must be taken care while using array in java

1> We cannot assign one reference variable to another at the same level or who does not have any inheritance relation . For ex-

int  arr [  ]  = new  byte [ 4 ] ;  // Invalid cannot store byte into int type . 

2> We cannot use + operator with the array reference for indicating the next member of the array because java do not deals with the address at the user level.

int  arr [  ]  = new  int [ 4 ] ;
( arr + 1 ) ;                          // Invalid in Java

3> Cannot assign direct a string value to a array reference . For ex-

String  arr  [ ] = " Java " ; 

The above statement is invalid and give compilation error saying " incompatible type " because compiler find the Java as a string type which is one of the class in java where as on the left side we have a String array. So it is " incompatible type " . Correct form is as following ,

String  arr  [ ] = { " Java " }  ; 

Now Java is a string is of array type. 

Available link for download