0

why there is an error (variable shadowing)

static void removeElement() { for (int a = 0;a<5;a++){ System.out.println(a); } int a = 0; System.out.println(a); }// this code can be executed ---------------------------------------------------------------------------------------------- static void removeElement() { int a = 0; for (int a = 0;a<5;a++){ System.out.println(a); } System.out.println(a); }// there is an error in this code why this happens (just the different position of int a?)

9th May 2021, 11:41 PM
Zhengrong Yan
Zhengrong Yan - avatar
1 Réponse
- 1
David Yan In the first example variable a is scope variable means that variable scope is within the loop only so you can't access outside the loop but you can declare same variable again outside the loop. Because of old variable scope was limited till loop only so new variable will not give any error and your code will work fine. In the second example variable a became global variable for loop so you can't redeclare same variable in loop. You can just write for(a = 0; a < 5; a++)
10th May 2021, 4:05 AM
A͢J
A͢J - avatar