Re: Variable scope and redefinitions
"biffta" <biffta@hotmail.com> wrote in message
news:1158012836.309443.210810@q16g2000cwq.googlegroups.com...
I came across the following code in a textbook and am a little puzzled
by it:
ArrayList<JCheckBox> checkboxList = new ArrayList<JCheckBox>();
for (int i = 0; i < 256; i++) {
JCheckBox c = new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
} // 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
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?
Thanks for reading!
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project