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 strings? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Immutable strings?" Watch "Immutable strings?" New topic

Immutable strings?

D Grove

Joined: Nov 17, 2004
Posts: 1
I can't understand this from the java almanac:

String str;
while ((str = in.readLine()) != null) {

what happens to str when it gets reloaded each time?
Something bad, correct?


Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


Welcome to JavaRanch!

"str" is a variable, not a String. A variable like "str" is a reference to a String; a way of saying "that String over there." Whereas Strings are immutable, references to Strings are not.

Short answer: nothing bad at all. The value of "str" changes over time; it refers to a new String each time through the loop. No problem.
[ November 17, 2004: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 805
To continue with Ernest's explanation, the Strings that str references are made available for garbage collection when str no longer refers to them.

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
I agree. Here's the link:
subject: Immutable strings?
It's not a secret anymore!