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
--Shweta<br />SCJP 1.4 <br />SCWCD
Joined: Feb 01, 2002
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