Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String can't initalize within a loop?

 
james falk
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all. Working on a project for school and am almost done with my first draft, but have run into a seemingly simple problem. This method is supposed to return a string. I didn't initialize the string at the top of the method because I had nothing to initialize it to per se. I then run a loop to give the string some data and return the string with a little addendum. I am getting a compiler error because the string has not been initialized, and I realize that the scope of s is permitted only to the loop, but i thought if i declared the string outside the loop and then modify it inside the loop, the compiler can recognize that as the same variable. i don't declare a new variable inside the loop(!), so what gives?



Thanks for any help guys and gals...
 
Wesleigh Pieters
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can simply fix this by initializing it to String s = "";

remember what happens with local variables?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Local variables must be initialized before you read them.

In your code, it's possible that "words" has length 0, in which case the body of the loop never executes, so s will be not initialized when line 11 is reached, where you read from s.
 
james falk
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, right. Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic