From here:
The answer is emphatically that str absolutely ought to be declared
within the while loop. No ifs, no ands, no buts.
The only case where this rule might be violated is if for some reason
it is of vital importance that every clock cycle must be squeezed out
of the code, in which case you might want to consider instantiating
something in an outer scope and reusing it instead of re-instantiating
it on every iteration of an inner scope. However, this does not apply
to your example, due to the immutability of strings in java: a new
instance of str will always be created in the beginning of your loop
and it will have to be thrown away at the end of it, so there is no
possibility to optimize there.
There's is a difference if the variable is a primitive or an object as explained with great detail here:
for primities... variables declared outside the loop you can do it
with no real fear of a performance hit. If you like it declared
outside the loop and want the best possible performance you can
declare it outside and not initialize it.
for objects... If an object is declared inside a loop the memory for
the object is allocated each time and the initialization for the
object is performed. The initialization may not take that much time
but the memory allocation will be. In some cases you may not be able
to get beyond creating a new object with every loop but if possible it
is better to reset the object and reuse it.