Why does the following work fine?
String str;
while (condition) {
str = calculateStr();
.....
}
But this one is said to be dangerou
Warning for almost everybody in this question: Here is sample code where inside the loop it can easily be 200 times slower on my computer with Java 7 (and the memory consumption is also slightly different). But it is about allocation and not only scope.
public class Test
{
private final static int STUFF_SIZE = 512;
private final static long LOOP = 10000000l;
private static class Foo
{
private long[] bigStuff = new long[STUFF_SIZE];
public Foo(long value)
{
setValue(value);
}
public void setValue(long value)
{
// Putting value in a random place.
bigStuff[(int) (value % STUFF_SIZE)] = value;
}
public long getValue()
{
// Retrieving whatever value.
return bigStuff[STUFF_SIZE / 2];
}
}
public static long test1()
{
long total = 0;
for (long i = 0; i < LOOP; i++)
{
Foo foo = new Foo(i);
total += foo.getValue();
}
return total;
}
public static long test2()
{
long total = 0;
Foo foo = new Foo(0);
for (long i = 0; i < LOOP; i++)
{
foo.setValue(i);
total += foo.getValue();
}
return total;
}
public static void main(String[] args)
{
long start;
start = System.currentTimeMillis();
test1();
System.out.println(System.currentTimeMillis() - start);
start = System.currentTimeMillis();
test2();
System.out.println(System.currentTimeMillis() - start);
}
}
Conclusion: Depending of the size of the local variable, the difference can be huge, even with not so big variables.
Just to say that sometimes, outside or inside the loop DOES matter.
According to Google Android Development guide, the variable scope should be limited. Please check this link:
Limit Variable Scope
You have a risk of NullPointerException
if your calculateStr()
method returns null and then you try to call a method on str.
More generally, avoid having variables with a null value. It stronger for class attributes, by the way.
Truly, the question stated above is an programming issue. How would you like to program your code? Where do you need the 'STR' to be accessed? There is no use of declaring a variable which is used locally as a global variable. Basics of programming I believe.
Declaring String str
outside of the while
loop allows it to be referenced inside & outside the while
loop. Declaring String str
inside of the while
loop allows it to only be referenced inside that while
loop.
Inside, the less scope the variable is visible into the better.