Because the scope of the variable is different in both case. The first one will be the instance variable which you can access only through the instance of the class(unless its static variable).The second one will be within the scope of the Main method. The compiler will complain only if you add duplicate instance variables or duplicate variable within the same scope (for ex. within a method). I hope the above explanation is right.
Also, adding to what Ramki said, local variable, already declared in an enclosing block and therefore visible in a nested block, cannot be redeclared in a nested block. A local variable in a block can be redeclared in a block if the blocks are disjoint. But this is not the case when the local & member variable have same name. Local variable shadows the member variable and takes priority. Regards Shweta
Hi shweta, Ok so that means the following code should not work because int i declared in LOOP method is visible to SECONDLOOP and hence declaring int i again in SECONDLOOP should throw Compilation error. I compiled the code using JDK 1.4 and it executed correctly with the following output -- Inside Loop method --> i : 1 Inside SecondLoop method --> i : 2
Arijit, Every method has its own local memory available. It does not matter when same named local variable is used in different methods. But the following code will give u erros
Arjit, In ur code, u have not created nested loop, rather u r calling an entirely different method & as Anup says every method has itz own local memory. Method secondloop() is not using the memory of loop(), so there will be no conflict. Arjit the following article from Cindy Glass may also help clearing some of your doubts. Not all Variables are created Equal - Cindy's Segment - a Whimsical View of the World
--Shweta<br />SCJP 1.4 <br />SCWCD
There is no greater crime than stealing somebody's best friend. I miss you tiny ad:
a bit of art, as a gift, the permaculture playing cards