0

Im reading a book for learning java fundamentals. In Strings section i have read immutable strings and i get it that strings in java are immutable But then i read the sentence that i wrote in question title,

But immutable strings have one great advantage: the compiler can arrange that strings are shared

How compiler can arrange that strings are shared, what does that really mean? How it is an advantage of immutable strings?

Thanks in advance.

1 Answers1

1

When a object is immutable same object can be used by two different threads as contents will not get changed and threads can use the same object between them,this saves compiler efforts of making new objects.

Thing with Strings is "they are stored in a pool" and if multiple threads request for a String ("abc" for example), jvm can return reference of only one String object every time and be sure that no thread gets stale copy of that object (yes because its immutable)

Hope this helps!

Good luck!

Vihar
  • 3,626
  • 2
  • 24
  • 47
  • First paragrph helped me so much to understand this but second is somewhat confusing because im very new to java. Can you explain it more? – Osama Bin Omar Apr 22 '15 at 12:27
  • 1
    for further reference you can have a look at http://www.journaldev.com/797/what-is-java-string-pool and accept the answer if it helped you – Vihar Apr 22 '15 at 12:32
  • Note that `str=new String("abc")` will not use the string pool but `str="abc"` will. – Tim B Apr 22 '15 at 14:50
  • @TimB yes absolutely right, but for a person who is new to Java and is trying to learn it , this is best explaination I could gather, and on further reading the 'book' OP should get acquainted with this fact – Vihar Apr 22 '15 at 14:53