File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes immutable or what? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "immutable or what?" Watch "immutable or what?" New topic

immutable or what?

ryan headley
Ranch Hand

Joined: Jun 28, 2000
Posts: 156
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.

Ryan Headley<br /><a href="" target="_blank" rel="nofollow"></a>
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
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!".

So much trouble in the world -- Bob Marley
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

When you code using the + or +=, the compiler uses the StringBuffer class, and the append() method of that class.


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"

Joined: Sep 29, 2000
Posts: 8521
Well . . . the effect is as though you had used an append, that is not necessarily what happens. 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.

"JavaRanch, where the deer and the Certified play" - David O'Meara
ryan headley
Ranch Hand

Joined: Jun 28, 2000
Posts: 156
Thanx guys...I was thinking that it would puke, I wasn't thinking that it would just change the reference.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: immutable or what?
It's not a secret anymore!