So I stumbled upon the following piece of Java code :
final String osName = System.getProperty("os.name");
I have read in several other StackOverFlow questions that the String class is actually immutable. So I asked myself the following thing, why is it the String declared final?
I am not very good with C++, but in order to understand what happens behind the scenes(in Java) I decided to see what would be the equivalent in C++.
If my understanding is correct making the String final in Java is equivalent in making a pointer in C++ being const, that is what the pointer variable points to cannot be changed. The limitation in Java is that you can change only the constness of the pointer to that String, but the chuck of memory the pointer points to is immutable.
So my question is am I correct or I am missing something else?
When we say that Java String(s) are immutable, it is because a String object cannot be modified once created. Instead, you must create (and assign a reference to) a new String when you want to modify a String reference. When you mark a String variable as final
you are additionally making the reference immutable.
You are correct in your assumption. String is immutable but without the final declaration the pointer can't be changed. So if you want to "change" the String variable you can do so but it will not actually change the object it will create a new object and point the pointer to the new object. Adding final makes it so you cannot do this it won't let you change the pointer reference and the String object that it points to is immutable so you cannot change a final String.
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