Topic: Is a Java String really immutable?
+Anonymous A — 12.6 years ago #31,485

We all know that String is immutable in Java, but check the following code:
String s1 = "Hello World";
String s2 = "Hello World";
String s3 = s1.substring(6);
System.out.println(s1); // Hello World
System.out.println(s2); // Hello World
System.out.println(s3); // World
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[])field.get(s1);
value[6] = 'J';
value[7] = 'a';
value[8] = 'v';
value[9] = 'a';
value[10] = '!';
System.out.println(s1); // Hello Java!
System.out.println(s2); // Hello Java!
System.out.println(s3); // World
Why does this program operate like this? Why is the value of s1 and s2 changed and not changed for s3?
Well?
C͙̱̪̦͎͖i̼̜̮͓ao̬̼,̘͈͇̗̞ ̰T͕͔̫̦͔͍h͉̲͍̠̭e͎̪̖͕̲̞̭ ͔͓̭̰̘D̥͓̘o̝̖͍̩̰͈c̭̳͈̗t͈͉̰͉̞o̞͔̥r.̦̦̙̼͉͍͕
| Poll option | Votes | Percentage | Graph |
| Sprite. | - | 0% | |
| Boners. | - | 0% | |
+Anonymous B — 12.6 years ago, 1 minute later[T] [B] #362,955
Hello World
·Anonymous A (OP) — 12.6 years ago, 1 minute later, 3 minutes after the original post[T] [B] #362,956
@previous (B)
> mad as hell
C̩̳̼̤̭̞̪i͎a̗̹̜̝̪o̹̺,̭̟ ͖̩T̥͇̪h̙̺͈̮͓̩ͅe̹̼ͅ D͓̮̙̞̗̹̣o̮̫̗̝̘ct̰̺ͅo͙r.̥̲̳̖
+Anonymous C — 12.6 years ago, 1 minute later, 4 minutes after the original post[T] [B] #362,957
no1 cars
·Anonymous B — 12.6 years ago, 9 minutes later, 14 minutes after the original post[T] [B] #362,958
@362,956 (A)
Field field = mad
+Anonymous D — 12.6 years ago, 7 hours later, 7 hours after the original post[T] [B] #363,043
Not doing your Java homework for you.
+Anonymous E — 12.6 years ago, 1 hour later, 8 hours after the original post[T] [B] #363,052
Want my notes?
+The Doctor !7MHPahvoGY — 12.6 years ago, 11 minutes later, 8 hours after the original post[T] [B] #363,055
@OP
Get laid, poindexter.
+Anonymous G — 12.6 years ago, 3 hours later, 12 hours after the original post[T] [B] #363,106
java sucks, i prefer c#
t(-___-t)
+Anonymous H — 12.6 years ago, 37 minutes later, 12 hours after the original post[T] [B] #363,108
@363,055 (The Doctor !7MHPahvoGY)
> Get laid, poindexter.
-----------
As a doctor, I support The Doctor's suicide.
Start a new topic to continue this conversation.
Or browse the latest topics.