Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final variable manipulation in Java

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?

like image 479
Dusk Avatar asked Aug 08 '09 21:08

Dusk


People also ask

Can a final variable be manipulated in Java?

No you can't.

What is the final variable in Java?

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.

What is final class variable method in Java?

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.

Can final variable be changed?

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.


1 Answers

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).

like image 108
Michael Borgwardt Avatar answered Oct 13 '22 00:10

Michael Borgwardt