Could anyone please tell me what is the meaning of the following line in context of Java:
final variable can still be manipulated unless it's immutable
As far as I know, by declaring any variable as final, you can't change it again, then what they mean with the word immutable in above line?
No you can't.
In Java, the final keyword is used to denote constants. It can be used with variables, methods, and classes. Once any entity (variable, method or class) is declared final , it can be assigned only once. That is, the final variable cannot be reinitialized with another value.
Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses.
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.
It means that if your final variable is a reference type (i.e. not a primitive like int), then it's only the reference that cannot be changed. It cannot be made to refer to a different object, but the fields of the object it refers to can still be changed, if the class allows it. For example:
final StringBuffer s = new StringBuffer();
The content of the StringBuffer can still be changed arbitrarily:
s.append("something");
But you cannot say:
s = null;
or
s = anotherBuffer;
On the other hand:
final String s = "";
Strings are immutable - there simply isn't any method that would enable you to change a String (unless you use Reflection - and go to hell).
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