Declaring variables inside or outside of a loop

Why does the following work fine?

String str;
while (condition) {
    str = calculateStr();
    .....
}

But this one is said to be dangerous/incorrect:

while (condition) {
    String str = calculateStr();
    .....
}

Is it necessary to declare variables outside the loop?

20 Answers
20

Leave a Comment