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?)
1 Antwort
- 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++)