Declaring variables inside or outside of a loop

前端 未结 20 2588
后悔当初
后悔当初 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条回答
  •  我寻月下人不归
    2020-11-22 02:36

    One solution to this problem could be to provide a variable scope encapsulating the while loop:

    {
      // all tmp loop variables here ....
      // ....
      String str;
      while(condition){
          str = calculateStr();
          .....
      }
    }
    

    They would be automatically de-reference when the outer scope ends.

提交回复
热议问题