Not limited to for loops, while loops, if-else statements, try-catch, etc. There are various "blocks", but variables that are used only in them should be declared in the block.
List<String> strList = new ArrayList<String>();
String str = new String(); //← This! !! !!
for (int i = 0 ; i <= 10 ; i++) {
str = i + "Th";
strList.add(str);
}
Since String str
is declared outside the for loop, it can also be used outside the for loop.
So it goes against the Java theory of "the scope is as small as possible!".
There were about two people who wrote this way, so I asked, "Why did you write this way?" Then
I wonder if it will save memory because I use the same
String str
: sparkles:
It's not a wrong idea in the sense that you don't create a lot of useless variables, though: sweat_smile: However, it is NG: ng: because the scope expands unnecessarily.
List<String> strList = new ArrayList<String>();
for (int i = 0 ; i <= 10 ; i++) {
String str = new String();
str = i + "Th";
strList.add(str);
}
Use String str
only inside a for loop.
Then, if you declare it in a for loop, the scope will be smaller.
Java has garbage collection for "free memory as soon as you finish using it", so a new String str
is created and released for each for loop.
Therefore, you don't have to be very conscious of memory.
Variables used only in the for loop are declared in the for loop.
Roughly speaking, if you get lost, try putting a variable inside the loop. If there is no error, you can leave it as it is.
In my case, I wonder if the program written in "Good example" will be organized so far.
List<String> strList = new ArrayList<String>();
for (int i = 0 ; i <= 10 ; i++) {
strList.add(i + "Th");
}
Recommended Posts