-3

I doubt Why strings are called immutable, because if give like this String s="hi" and in the next line, we give s="hello" the value of s will change right please help me to understand anyone.

Karan_raj
  • 1
  • 4
  • 1
    Because `"hi"` and `"hello"` are immutable; you are creating two distinct `String` instances and assigning them to a single **reference** variable. `final String s = "hi";` would make the `s` reference immutable. – Elliott Frisch Nov 01 '20 at 05:21
  • It really doesn't matter why they are immutable. However, immutable objects work better with multiple threads. – NomadMaker Nov 01 '20 at 06:10

3 Answers3

2

When you define a String variable with a literal ("hi") like this:

String s = "hi"

you actually create a String object with an array of characters underneath. s is only the reference to this object in memory. Java does not allow to change String object itself (internal array). You can only assign s another object (s = "hello").

Let's say you have following:

String s = "hi";
String s2 = s;
s = "hello";

Here you do not change s2. It is still the same, still points to the "hi". You only changed the s, now it points to new String object - "hello".

Timur Levadny
  • 510
  • 4
  • 13
1

A String variable contains a reference to a String.

So when you assign a new value to a String variable, you are changing the reference, not the String itself.

Or in another words, the assignment makes the variable refer to a different string without changing the original string in any way. (It can't change the original string because strings are immutable.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Strings created using String class are immutable i.e. once created cannot be modified. This may seem to be a serious restriction on String initially . However, that is not the case . If you alter the existing string the new string gets created in the pool of strings and old one gets discarded . This is how the string class is designed , because the java developers realized that creating a new string is much more efficient than modifying the existing one.

Makarand
  • 477
  • 1
  • 7
  • 17