Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java final String, C++ equivalent. Is my understanding correct?

Tags:

java

c++

string

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?

like image 735
Evdzhan Mustafa Avatar asked Dec 25 '22 04:12

Evdzhan Mustafa


2 Answers

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.

like image 101
Elliott Frisch Avatar answered Dec 28 '22 23:12

Elliott Frisch


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.

like image 35
brso05 Avatar answered Dec 28 '22 23:12

brso05