> I came across the following code in a textbook and am a little puzzled
> by it:
> for (int i = 0; i < 256; i++) {
> JCheckBox c = new JCheckBox();
> } // end loop
>
[quoted text clipped - 6 lines]
> The compiler would report an error. I presume it has something to do
> with the scope within the for loop?
Yes. c goes out of scope for each iteration.
> That kind of makes sense I suppose
> but what about when you leave the loop, what is the name of the
> variable at first position of checkboxList? Or the second or the third?
> Or is it simply that it doesn't matter because it is only a reference
> to a JCheckBox?
Correct again.
Arne
>I came across the following code in a textbook and am a little puzzled
> by it:
[quoted text clipped - 12 lines]
>
> } // end loop
Consider a slightly different way of writing the same thing:
for (int i = 0; i < 256; i++) {
JCheckBox c;
c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
}
Note that "c" is not being re-declared, but just re-assigned.
> My question is this; How can you re-declare the variable c over and
> over? I mean if you were to write:
>
> JCheckBox c = new JCheckBox();
> JCheckBox c = new JCheckBox();
> The compiler would report an error. I presume it has something to do
> with the scope within the for loop? That kind of makes sense I suppose
[quoted text clipped - 5 lines]
> Thanks for reading!
>

Signature
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
biffta - 12 Sep 2006 12:30 GMT
> Consider a slightly different way of writing the same thing:
> for (int i = 0; i < 256; i++) {
[quoted text clipped - 6 lines]
>
> Note that "c" is not being re-declared, but just re-assigned.
I created an image which I hope correctly illustrates this code.
http://www.hopkins81.com/wp-images/scope-variables.PNG
I guess my confusion arose from having an arrayList full of C's but I
think now that this just doesn't matter!