Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

immutable or what?

 
ryan headley
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the following code compile and run correctly if Strings are immutable and can't be modified?

It's been a while since I've been working with just the basics, but apparently I need to...heh
I am running JDK 1.3, Win98.
Thanks
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan, strings are immutable.
What s = (s + "from java") is doing is that it's creating another string and "s" is now referencing that new string, which is "This is a test! from java" it no longer points to "This is a test!".
Bosun
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you code using the + or +=, the compiler uses the StringBuffer class, and the append() method of that class.

eg:

1 String s = new String("Hello");
2 s+="World";

Line 2 gets translated by the compiler into:
2 s = new StringBuffer(s).append("World).toString();

[This message has been edited by Mike Curwen (edited March 30, 2001).]
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well . . . the effect is as though you had used an append, that is not necessarily what happens.
15.18.1.2 Optimization of String Concatenation
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To
increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of
intermediate String objects that are created by evaluation of an expression.


 
ryan headley
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx guys...I was thinking that it would puke, I wasn't thinking that it would just change the reference.
Ryan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic