Following is a code where I have tried to change the value of a final variable. First it prints "a" then "ab". So, if we can change the value of a final variable then what's the benefit of declaring a variable as final? what is use of final key word then? Please any one can help me with this?????
package test_new;
public class FinalVarValueChange {
public static void main(String[] args){
final StringBuffer s=new StringBuffer("a");
System.out.println("s before appending :"+s);
s.append("b");
System.out.println("s after appending :"+s);
}
}
The only difference between a normal variable and a final variable is that we can re-assign the value to a normal variable but we cannot change the value of a final variable once assigned.
Finally, with the static final variable, it's both the same for each class and it can't be changed after it's initialized.
If a variable is declared with the final keyword, its value cannot be changed once initialized.
StringBuffer is mutable according to it's design, and method append is just a method to change it's content.
What final variable means in Java is:
For object, it means you can not assign another object to this reference, but it does not stops you from invoking methods of this object.
For basic type variables(int, float, boolean etc), since there's no reference and pointer, and object method here, so it simply means you can not change value of the variable.
Take the follow codes
final ObjectA objA = new ObjectA();
You can of course invoke methods of this object like below
objA.setXXX() //legal for a final variable objA
The side effect of setXXX() method is not controlled by final keyword here.
But for the follow code
final int a = 123;
You will not be able to assign any new value to this variable as below
a = 234; //Not legal if a has been defined as a final int variable.
But if you are defining it using Integer as below
final Integer a = new Integer(123);
You will be able to invoke methods of object a as below
a.xxx()
General speaking final definition is different for object and basic variable.
final
does not enforce any degree of constancy of the object to which a reference is referring (it is not the same as const
in C++).
When you mark a variable as final
, it means that you cannot assign a different object reference to that variable.
For example, this code will not compile:
final StringBuffer s=new StringBuffer("a");
s = new StringBuffer("another a"); /*not possible to reassign to s*/
It can be useful when using Runnables, Callables and locking idioms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With