Java scope and lifetime of variable

2019-01-29 11:19发布

问题:

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.