Java scope and lifetime of variable

僤鯓⒐⒋嵵緔 提交于 2019-11-28 12:12:32

问题


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);
    }
}
}

回答1:


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.




回答2:


1.The 'if' statement can change the value of the 'isprime' variable

Yes.The inner if can change isprime

2.However, is this change not forgotten once the inner 'for' code block {} is left?

No.It is not forgotten.

3.This would mean that isprime would remain true and all numbers would be displayed.

This can happen only if your second question (No.2) is forgotten

Think of it.A global variable can be changed by any methods as the scope of it is the whole program.This variable can be changed by any method. Similarly,isprime can be changed in main as it is declared in main and the scope of it is in main.



来源:https://stackoverflow.com/questions/26954849/java-scope-and-lifetime-of-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!