That is because of scope of a variable,
Case1:
public class Test
{
public static void main(String[] args)
{
int i=3;
int i=4;
System.out.println(i);
}
}
In here you have a variable i defined in the same scope twice.
Case2:
public class Test
{
public static void main(String[] args)
{
for(int a=0;a<9;a++)
{
int b=a+1;
System.out.println(b);
}
}
}
In here there will be only one b instance at a time, the moment the loop ends the variable is destroyed and recreated for the next iteration. So you will not get the error that you are looking for.
I suggest you to go through scope of variables in JAVA.
Note: I would not suggest this way of programming, as resource is getting wasted for creating the same variable again and again. all you do is reset it within the loop.
Update
public class Test1 {
public static void main(String[] args) {
Person p1=new Person();
System.out.println("Person Object p1 before for loop "+p1);
for(int i=0;i<5;i++){
Person p2=new Person();
System.out.println("Person object "+i+" "+p2);
}
System.out.println("Person Object p1 after for loop "+p1);
}
}
Dummy class Person
class Person{ }
Output
Person Object p1 before for loop com.project.CVS.Person@fd13b5
Person object 0 com.project.CVS.Person@118f375
Person object 1 com.project.CVS.Person@117a8bd
Person object 2 com.project.CVS.Person@471e30
Person object 3 com.project.CVS.Person@10ef90c
Person object 4 com.project.CVS.Person@a32b
Person Object p1 after for loop com.project.CVS.Person@fd13b5
Here I have created a dummy class called Person and I have declared and initialized a Person object within a loop. Now, When I print out the person object, it gives out the hash code.
Now on analyzing the output one can clearly see that new object is getting created during every iteration, as the hash code values are not matching. If your application is really not needing such implementation then, you must and should avoid it. I hope i have cleared your doubt.