This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Immutable strings?" Watch "Immutable strings?" New topic
Author

Immutable strings?

D Grove
Greenhorn

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

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

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

Thanks!

Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

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: 804
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...)
 
 
subject: Immutable strings?
 
Similar Threads
Dynamic Method Call
casting
static object initialization
How to session in jsp
How many objects will be created