Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

'final' keyword for array

 
utsav gupta
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vivek Singh wrote:What do you mean by object state...please explain.

You might think of it as the contents of the object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic