简体   繁体   中英

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

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.

Java differs in a number of ways.

In Java you can never alter a String 's contents after creation - it is immutable . Also the Java reference is essentially equivalent to a C++ pointer. But in C++ you can change the contents of a std::string unless it is declared const .

Putting that together:

String s = "stuff"; // Java
const std::string* s = new std::string("stuff"); // C++

Now making a Java reference final in Java means you can not change the reference to point to a different String . That is equivalent to making the pointer const in C++:

final String s = "stuff"; // Java
const std::string* const s = new std::string("stuff"); // C++

Also Jave manages memory automatically for its String s. This can be roughly approximated in C++.

Like this:

String s = "stuff"; // Java
std::shared_ptr<const std::string> s =
    std::make_shared<const std::string>("stuff"); // C++

and

final String s = "stuff"; // Java
const std::shared_ptr<const std::string> s =
    std::make_shared<const std::string>("stuff"); // C++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM