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 do String s2="hello"; then
another object will not be created but s2 will point to hello
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?

13 Answers
13

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *