简体   繁体   中英

Java scope and lifetime of variable

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM