首页 > 解决方案 > why i can make few file object in for loop at java

问题描述

In the following code I can make f object 4 times without error

for(i=0;i<3;i++){
   File f2=new File("D:/"); 
}

but java take error for this code for second line because one time we maked object f

File f = new File("D:/");
File f = new File("C:/");

why in lopp we can make file object many times with the same name and the same constructor but at second script we can't do it?

标签: javafilefor-loopfile-io

解决方案


Your loop is equivalent to the following code:

{ // block 1 start
    File f2 = new File("D:/");
} // block 1 end

{ // block 2 start
    File f2 = new File("D:/");
} // block 2 end

{ // block 3 start
    File f2 = new File("D:/");
} // block 3 end

Each f2 variable is limited to it's block and is only existent inside of it. However if you try to declare one variable two times in one block it will fail.


推荐阅读