Alex Rivera | Logout

Declaring variables inside or outside of a loop

Asked 2012-01-10T13:01:15.730
284

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?

Edit
Report

1 Answer

-2

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.

answered 2012-11-22T10:12:13.563

Your Answer