Shadowing |
| INTERMEDIATE |
If you declare a variable in a block that has the same name as a variable outside the block, the variable inside the block shadows (hides) the variable outside the block.
int x = 1; System.out.println(x); // prints 1 { String x = "hello"; System.out.println(x); // prints "hello" } System.out.println(x); // prints 1
Shadowing allows you to write code without having to know the names of all the other variables in the class.
It is very poor style to intentionally shadow a variable. However, it is legal, so if you accidently shadow a variable you will not get an error message.