"Manipulating final variables"
Hi,
I was going through a Java book, where I came across this statement:
"Final variable can be manipulated unless it's immutable."
What do this mean? If it can be manipulated can you give an example?
Thanks.
Hi,
I was going through a Java book, where I came across this statement:
"Final variable can be manipulated unless it's immutable."
What do this mean? If it can be manipulated can you give an example?
Thanks.
final int[] fred = {0,1,2,3,4};
fred[2] = 7;
The reference is final and cannot be changed but the object it points to can be internally modified.
What book?
Maybe you should include the entire paragraph containing this sentence for some context.
But, AFAIK, (aside from reflection maybe) the value of a final variable can only be set once per instance, or once period if also static.
Edit: Nevermind, I think sabre just hit on the exact point that book was attempting to make. And now that I read both your posts, I agree with him.
Just to explain in few more words...
A variable can be declared final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment.
A blank final is a final variable whose declaration lacks an initializer.
If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object. This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.
> > final int[] fred = {0,1,2,3,4};
> fred[2] = 7;
>
>
> The reference is final and cannot be changed but the
> object it points to can be internally modified.
That's why, in this cases, you should make defensive copies:
public class A {
private final int[] fred = {0, 1, 2, 3, 4};
/**
* @return the fred
*/
public int[] getFred() {
return fred.clone();
}
/**
*
*/
public A(){
}
Now, even if you do something like this
public static void main(String[] args) {
A a = new A();
System.out.println(a.getFred()[2]);
a.getFred()[2] = 3;
System.out.println(a.getFred()[2]);
}
the output is
2
2
Manuel Leiria
> > The reference is final and cannot be changed but
> the
> > object it points to can be internally modified.
>
> That's why, in this cases, you should make defensive
> copies:
>
A perfectly valid point but I suspect that this will just confuse the OP.
> A perfectly valid point but I suspect that this will
> just confuse the OP.
You're probably right! I just felt I had to tell him.
Manuel Leiria