• Post Reply Bookmark Topic Watch Topic
  • New Topic

Immutable strings?  RSS feed

 
D Grove
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To continue with Ernest's explanation, the Strings that str references are made available for garbage collection when str no longer refers to them.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!