File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes 'final' keyword for array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark " Watch " New topic
Author

'final' keyword for array

utsav gupta
Ranch Hand

Joined: Mar 19, 2009
Posts: 57
hi
If I use final keyword with an array i'm still able to change the contents of array . Can you please tell why is it happening?

final int[] a = {1,2,3}

a[0]++; //changes value of a[0] to 1.

Thanks
Utsav

Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

That's the rule. The "final" keyword, when applied to a variable, says that you can't change the variable. So in your case, code which tries to change the variable "a" would not be allowed. This, for example:

after the declaration you posted would be illegal.

Now, don't confuse the variable with the object it refers to. In this case the object it refers to is an int array. You can't change the variable, but you can change the object's state. You showed an example of that already.
Vivek Singh
Ranch Hand

Joined: Oct 27, 2009
Posts: 92
Paul Clapham wrote:That's the rule. The "final" keyword, when applied to a variable, says that you can't change the variable. So in your case, code which tries to change the variable "a" would not be allowed. This, for example:

after the declaration you posted would be illegal.

Now, don't confuse the variable with the object it refers to. In this case the object it refers to is an int array. You can't change the variable, but you can change the object's state. You showed an example of that already.

What do you mean by object state...please explain.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

Vivek Singh wrote:What do you mean by object state...please explain.

You might think of it as the contents of the object.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: 'final' keyword for array