Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why String is immutable or final in Java [duplicate]

As i was told this is important String Interview question in Java, which starts with discussion of " What is String ", how String is different in java than in C or C++ and then you are asked about immutable objects and you're asked the main question: " Why String is immutable or final in Java ".

Can you share your Ideas ?

Thanks in advance.

like image 255
Jilberta Avatar asked Apr 12 '13 09:04

Jilberta


2 Answers

It is mainly for security reasons. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable

Immutability of String solves some synchronization issues, it makes the String thread safe

To support StringPool facility

To cache the hashcode of String

To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded

like image 174
Mohan Raj B Avatar answered Oct 26 '22 23:10

Mohan Raj B


The two main reasons why strings are immutable in many modern languages, including Java, are security and performance (or, more precisely, chance for optimizations).

The fact that strings are final is to ensure their immutability (by forbidding anyone from extending them and making them mutable again).

like image 39
Theodoros Chatzigiannakis Avatar answered Oct 26 '22 23:10

Theodoros Chatzigiannakis