Java final String, equivalent to C ++. Do I understand correctly?

So, I came across the following piece of Java code:

final String osName = System.getProperty("os.name");

I read on several other StackOverFlow questions that the String class is actually immutable. So I asked myself the following: why is the string declared final?

I am not very good at C ++, but in order to understand what is going on behind the scenes (in Java), I decided to see what would be equivalent in C ++.

If my understanding is correct, then ending a line in Java is equivalent to having a pointer in C ++ as a constant, then what the pointer of a pointer indicates cannot be changed. The limitation in Java is that you can only change the pointer constant to this string, but the memory patch pointed to by the pointer is unchanged.

So my question is: am I right, or am I missing something else?

+4
source share
3 answers

When we say that Java strings are immutable, this is because the String object cannot be changed after creation. Instead, you should create (and assign a link) a new String if you want to change the link to String. When you mark a String variable as final, you also make the link immutable.

+6
source

. , . , "" String, , , . final , , , String, , , .

+4

Java .

Java String - . Java ++. ++ std::string, const.

:

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

Now, creating a Java link finalin Java means that you cannot change the link to point to another String. This is equivalent to creating a const pointer in C ++:

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

Jave also automatically manages memory for Strings. This can be approximated approximately 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++
0
source

All Articles