+ 24

Why strings are immutable in Java?

28th Jul 2017, 5:00 AM
Amir
Amir - avatar
4 odpowiedzi
27th Jan 2018, 7:26 PM
ASIF BILAKHIYA
ASIF BILAKHIYA - avatar
+ 11
String is immutable for several reasons, here is a summary: Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed. Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues. Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object). Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
28th Jul 2017, 5:38 AM
Stacy
Stacy - avatar
+ 8
Good answer, Stacy. An additional advantage might be this: immutable strings are better suited as hash map keys.
20th Jan 2018, 7:04 AM
Eric Blinkidu
Eric Blinkidu - avatar
+ 2
what are parameters
5th Aug 2017, 5:26 PM
Ruchitha Reddy
Ruchitha Reddy - avatar