Why string class is immutable in java

Give me correct answer with real time example it's very Argent to me

Your Answer

String creation in Java uses String pool(part of Heap memory in Java)

string a = "Hello"; // "Hello" is created in string pool.
string b = "Hello"; // Now this refers a's value instead of creating new one in string pool.

means when same string is used, they shares the single memory.
when a is reassinged with another string.
eg : a = "Bye";
now b is still pointing towards the same pointer address of "Hello"

a is just now pointing towards new address in string pool called "Bye".

Conclusion : A single string can be assigned with any number of string variables.
if the old string is destroyed when variable is reassigned with new string. all other string variables holding the same memory address looses their value.

I believe this help.
sorry If I'm wrong.

Core Java

Didn't get the answer.
Contact people of Talent-Core Java directly by clicking here