Why String is immutable or final in Java

As I was told, this is an important question about setting a String in Java, which starts with a discussion of β€œWhat is a String”, how does String differ in java than in C or C ++, and then you are asked about immutable objects, and you asked the main question : "Why is String immutable or final in Java."

Can you share your ideas?

Thanks in advance.

+7
source share
3 answers

This is mainly for security reasons . String is used as a parameter in a network connection, the URL of the database, etc. It can be easily attacked if modified.

String solves some synchronization problems, makes String thread safe on stream

To support StringPool object

The hashcode String cache

To support the loading mechanism of a class in which String used as an argument. A string that is mutable will load the wrong class.

+26
source

The two main reasons strings are immutable in many modern languages, including Java, are security and performance (or rather, the likelihood of optimization).

The fact that the final strings is to ensure their immutability (forbidding anyone to extend them and change them again).

+8
source

The most important reason is security .

There will be many security risks if a malicious thread can get a link to a mutable string, which must be passed to a method that must check the string before it performs an important operation. It would be possible for the thread to change the string after checking it, and then the operation would be performed using a dangerous string.

Another reason why String is immutable in Java is to allow String to cache its hash code.

As mentioned above, the most important reason is thread safety and security .

Consider a scenario in a banking application for transferring money - the recipient's account number is defined in the line as "0789567345". If by mistake / intentionally it acc. number is changed, the money will go to the wrong account.

Another scenario is if someone changes the class name somewhere between processing, like ..

 getClass().getName().subString(0, 5); 

The class loader will just say "Class Not Found

+8
source

All Articles