Details of memory in for and while in Java
Wen / Zhu Jiqian
Java program structure has sequence structure, loop structure, branch structure and jump structure, and the following are often used in loop structure: for loop, while loop and do while loop. This paper mainly discusses the difference between for loop and while loop. In fact, they are interchangeable in the daily programming process. The only difference lies in the format. If the loop control needs to be carried out through variables, and the variables used only exist as loop increments, the two will be different in memory.
When using while for loop control, variables are often used to define a member variable, such as I in the screenshot. Its value will exist in heap memory and will always exist with the existence of the class. Even if the loop ends, it will not be released automatically. It will disappear only when the class ends. In other words, it will occupy memory.
When using for loop, if variables are needed for loop control, a local variable is often defined, similar to the following screenshot:
The variable J here belongs to a local variable, and the defined value is stored in the stack memory. When the loop ends, it will automatically release the value of J, that is, it will not continue to occupy space.
It can be seen that although both for loop and while loop can be interchanged, in terms of details, there is still a problem of whether to occupy memory. Compared with while, for occupies less space when variables are required for loop control. In fact, we need to pay attention to the problem of space occupation. After all, it involves program optimization.