Friday, September 21, 2007

static final String[] is not final ?

Lets take final variable and try to assign new value to it. Well , we 'll have no luck here - "cannot assign a value to final variable myVar" yet at compilation stage. But having a deal with final arrays is something different. Here is an example :

class FinalArray
{
public static final String[] array = {"a", "b","c"};
public static void main(String args[])
{
array[0] = "aaa";
System.out.println(array[0]);
}
}
Output will be "aaa". It is still not possible to do something like

String[] some_array = {"aaa", "bbb","ccc"};
array = some_array;

but possible per-element assigning new values to final array elements:
class FinalArray
{
public static final String[] array = {"a", "b","c"};
public static void main(String args[])
{
String[] some_array = {"aaa", "bbb","ccc"};
for(int i=0;i<length;i++)
{
array[i] = some_array[i];
}

for(String element: array)
{
System.out.println(element);
}
}
}
So, it is final, you say ?