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);
}
}
}
Yes.The inner
if
can changeisprime
No.It is not forgotten.
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 inmain
as it is declared inmain
and the scope of it is inmain
.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.