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 String can't initalize within a loop? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String can Watch "String can New topic

String can't initalize within a loop?

james falk
Ranch Hand

Joined: Nov 02, 2012
Posts: 55
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

Joined: Sep 04, 2012
Posts: 81
you can simply fix this by initializing it to String s = "";

remember what happens with local variables?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15093

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
james falk
Ranch Hand

Joined: Nov 02, 2012
Posts: 55
Ah, right. Thanks!
I agree. Here's the link:
subject: String can't initalize within a loop?
It's not a secret anymore!