Reputation: 29
I'm new to android and currently learning the basics. the code below is meant to display a list of numbers (1-10). I want to understand why the code runs with no errors in android studio and it actually displays the list. From what I see, we are declaring the variable wordView multiple times without changing the variable name. Are we updating the same WordView variable each time? if so, how am I getting a list?
LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);
int index = 0;
while (index < 10) {
TextView wordView = new TextView(this);
wordView.setText(words.get(index));
rootView.addView(wordView);
index ++;
}
Upvotes: 2
Views: 85
Reputation:
Declaring a variable inside a loop makes the variable only available in the scope of that instance in the loop. Basically, each iteration of the loop, the variable gets created and goes out of scope (is "forgotten") at the end of the iterations.
Upvotes: 2
Reputation: 11477
You can gracefully define a variable within a loop the scope of the variable is only till each iteration. In each iteration a new object of type TextView is created but
Remember
you cannot declare a variable within if
statement
if (index < 10) {
TextView wordView = new TextView(this);
wordView.setText(words.get(index)); // this will throw compile time error..
}
Upvotes: 1
Reputation: 121998
Scope matters.
In each iteration a new Object
of TextView
gets created and died in the same iteration as the scope ends there in the same iteration.
while (index < 10) {
TextView wordView = new TextView(this);
wordView.setText(words.get(index));
rootView.addView(wordView);
index ++;
}
Variable wordView
gets created and ends in the same iteration.
while (index < 10) {
TextView wordView = new TextView(this); // created
wordView.setText(words.get(index));
rootView.addView(wordView);
index ++;
// died here
}
As soon as the scope end, garbage collector catches that instance as there is no reference of it anymore.
Upvotes: 1