Java范围和变量的生命周期 [英] Java scope and lifetime of variable
问题描述
我编写了以下程序来显示2到50(含)之间的所有素数。该程序按预期运行,但当我重新检查代码时,我想知道为什么它没有失败。 if
语句可以更改 isprime
变量的值。但是,一旦内部 for
代码块{}被遗忘,这个改变是否会被遗忘?这意味着 isprime
将保持 true
并显示所有数字。
I wrote the following program to display all prime numbers between 2 and 50 (inclusive). The program ran as intended but when I reexamined the code I wondered why it had not failed. The if
statement can change the value of the isprime
variable. However, is this change not forgotten once the inner for
code block {} is left? This would mean that isprime
would remain true
and all numbers would be displayed.
class Prime {
public static void main (String args []) {
int a, b;
boolean isprime;
for (a = 2; a < 51; a++) {
isprime = true;
for (b = a-1; b > 1; b--) {
if (a % b == 0) isprime = false;
}
if (isprime) System.out.println(a);
}
}
}
推荐答案
嗯,正如您所见,这不是它的工作原理:变量的范围是声明它的块,包括任何子块。
Well, as you see, that's not how it works: the scope of the variable is the block where it is declared, including any sub block.
修改子块中的变量会修改它的所有范围。每次新块开始时都不会生成变量的副本。
Modifying the variable in a sub block modifies it for all of its scope. A copy of the variable is not made everytime a new block starts.
这篇关于Java范围和变量的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!