Jump to content

Please explain this code.

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
isuru

isuru

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 233 posts
Please someone explain this code. I wrote it, but I can't clarify what it does.

package test;


import java.io.File;

import java.io.IOException;


public class Main  {


    public static void main(String args[]) throws IOException

    {

        File dir = new File("D:\\new");

        String[] files = dir.list();


        for(String file : files)

        {

            System.out.println(files);

        }

    }


}

I can write that in this way, right?

 for(int i = 0; i < files.length; i++)

        {

            String fileName = files[i];

            System.out.println(files);

        }

Thanks in advance!
Lost!

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
What you wrote is called the foreach-loop.
for(String file : files){   }
Read like: "for each 'file' of type String in the array/collection 'files' do the following".
Every loop it takes the next object from the array/collection and puts it in the variable, here "file".

The two loops you've given indeed do the same. A foreach loop is quicker to write imo, but has less capabilities. For isntance you may not change the array/collection you are looping trough and you also don't have an index/counter you usually have in a "normal" for-loop

#3
Roman Y

Roman Y

    Programmer

  • Members
  • PipPipPipPip
  • 189 posts
Strange code... for one I don't get why main is throwing the exception... should be try-catch around the new File(..); though...

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
The try catch is not required, it won't throw an error if the file doesn't exist. You can do .exists() on a file object to check for that.

#5
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
for(String file : files)
{
    System.out.println(files);
}

This prints the "files" object.
I believe you were looking for
for(String file : files)
{
      System.out.println(file)
}
"file" instead of "files".

#6
mr mike

mr mike

    Learning Programmer

  • Members
  • PipPipPip
  • 96 posts
Roman Y
The exception after main is just showing that you know the code could throw an IOException
This is so you do not need a try/ catch block for an IOException with File.