I was asked in an interview why String is immutable
I answered like this:
When we create a string in java like
String s1="hello";
then an object will be created in string pool(hello) and s1 will be pointing to hello.Now if again we doString s2="hello";
then another object will not be created but s2 will point tohello
because JVM will first check if the same object is present in string pool or not.If not present then only a new one is created else not.
Now if suppose java allows string mutable then if we change s1 to hello world
then s2 value will also be hello world
so java String is immutable.
Can any body please tell me if my answer is right or wrong?
If
HELLO
is your String then you can't changeHELLO
toHILLO
. This property is called immutability property.You can have multiple pointer String variable to point HELLO String.
But if HELLO is char Array then you can change HELLO to HILLO. Eg,
Answer:
Programming languages have immutable data variables so that it can be used as keys in key, value pair. String variables are used as keys/indices, so they are immutable.
From the
Security
point of view we can use this practical example:The most important reason of a String being made immutable in Java is Security consideration. Next would be Caching.
I believe other reasons given here, such as efficiency, concurrency, design and string pool follows from the fact that String in made immutable. For eg. String Pool could be created because String was immutable and not the other way around.
Check Gosling interview transcript here
I read this post Why String is Immutable or Final in Java and suppose that following may be the most important reason:
String
is immutable for several reasons, here is a summary:String
in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.String
is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).That being said, immutability of
String
only means you cannot change it using its public API. You can in fact bypass the normal API using reflection. See the answer here.In your example, if
String
was mutable, then consider the following example:String class is
FINAL
it mean you can't create any class to inherit it and change the basic structure and make the Sting mutable.Another thing instance variable and methods of String class that are provided are such that you can't change
String
object once created.The reason what you have added doesn't make the String immutable at all.This all says how the String is stored in heap.Also string pool make the huge difference in performance