TinyChan

Topic: Is a Java String really immutable?

+Anonymous A12.6 years ago #31,485

1335070606482717.jpgWe 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 B12.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

133338833815617.jpg@previous (B)
> mad as hell

C̩̳̼̤̭̞̪i͎a̗̹̜̝̪o̹̺,̭̟ ͖̩T̥͇̪h̙̺͈̮͓̩ͅe̹̼ͅ D͓̮̙̞̗̹̣o̮̫̗̝̘ct̰̺ͅo͙r.̥̲̳̖

+Anonymous C12.6 years ago, 1 minute later, 4 minutes after the original post[T] [B] #362,957

no1 cars

·Anonymous B12.6 years ago, 9 minutes later, 14 minutes after the original post[T] [B] #362,958

@362,956 (A)
Field field = mad

+Anonymous D12.6 years ago, 7 hours later, 7 hours after the original post[T] [B] #363,043

Not doing your Java homework for you.

+Anonymous E12.6 years ago, 1 hour later, 8 hours after the original post[T] [B] #363,052

Want my notes?

+The Doctor !7MHPahvoGY12.6 years ago, 11 minutes later, 8 hours after the original post[T] [B] #363,055

ChristopherEccleston.jpg@OP

Get laid, poindexter.

+Anonymous G12.6 years ago, 3 hours later, 12 hours after the original post[T] [B] #363,106

java sucks, i prefer c#
t(-___-t)

+Anonymous H12.6 years ago, 37 minutes later, 12 hours after the original post[T] [B] #363,108

phil-domestos.jpg@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.

:

You are required to fill in a captcha for your first 5 posts. Sorry, but this is required to stop people from posting while drunk. Please be responsible and don't drink and post!
If you receive this often, consider not clearing your cookies.



Please familiarise yourself with the rules and markup syntax before posting.