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 ?

7 comments:

salman khattak said...

final object does not mean immutable! final only means you cannot create a new or re-point to another instance of the object... background on pointers and memory addresses comes in handy here.

Stas Ostapenko said...

Hi Salman, thanks for comment.

Well, you are rigth. Java Language Spec is very heplful here :

http://java.sun.com/docs/
books/jls/third_edition/
html/typesValues.html#4.12.4

But in some situations static final Object[] could be security hole...

Jay said...

If you want the elements to be immutable, make it an immutable collection.

Stas Ostapenko said...

Hi Jim !

Yep, I see... There are a few methods with names starting with unmodifiable* at java.util.Collections. It seems to be it is the best choise to provide read-only data for user.

Christoph said...

Is there a way to create a multidimensional array in Java as a constant? It seems that this is not possible

Stas Ostapenko said...

@Christoph

I think you should consider immutable collections.

Ivan Sit said...

dw