Declaring variables inside or outside of a loop

前端 未结 20 2592
后悔当初
后悔当初 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:47

    The str variable will be available and reserved some space in memory even after while executed below code.

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

    The str variable will not be available and also the memory will be released which was allocated for str variable in below code.

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

    If we followed the second one surely this will reduce our system memory and increase performance.

提交回复
热议问题