Why does the following work fine?
String str;
while (condition) {
str = calculateStr();
.....
}
But this one is said to be dangerou
Declaring objects in the smallest scope improve readability.
Performance doesn't matter for today's compilers.(in this scenario)
From a maintenance perspective, 2nd option is better.
Declare and initialize variables in the same place, in the narrowest scope possible.
As Donald Ervin Knuth told:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"
i.e) situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.