Declaring variables inside or outside of a loop

前端 未结 20 2097
后悔当初
后悔当初 2020-11-22 01:59

Why does the following work fine?

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

But this one is said to be dangerou

20条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:46

    If you don't need to use the str after the while loop (scope related) then the second condition i.e.

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

    is better since if you define an object on the stack only if the condition is true. I.e. use it if you need it

提交回复
热议问题