Java Java Data Structures Efficiency! Custom Serialization

Maxwell Nelson
Maxwell Nelson
9,465 Points

String[] args in a method.

Hello!

I am trying to understand using String[] args within a method. Below is a load method for a txt file utilized in the Karaoke project.

public void importFrom(String fileName) {
    try (
        FileInputStream fos = new FileInputStream(fileName);
        BufferedReader reader = new BufferedReader(new InputStreamReader(fos));
    ) {
        String line;
        while((line = reader.readLine()) != null) {
            String [] args = line.split("\\|");
            addSong(new Song(args[0], args[1], args[2]));
        }
    } catch(IOException ioe) {
        System.out.printf("Problem loading %s %n", fileName);
        ioe.printStackTrace();
    }
}

in the middle of the code block, there is

        String line;
        while((line = reader.readLine()) != null) {
            String [] args = line.split("\\|");
            addSong(new Song(args[0], args[1], args[2]));
        }

Can someone explain what is going on here? I understand everything before and after but would appreciate a more detailed explanation than the one given in the video.

Thank you!

1 Answer

With the square brackets you tell the JVM that you don't just need one string, but an ARRAY of strings (multiple Strings, so that you can access those independently).

Info: You can also place the brackets after the array's name: String args[]

Here you can get more Info: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html http://alvinalexander.com/java/java-string-array-reference-java-5-for-loop-syntax

Maxwell Nelson
Maxwell Nelson
9,465 Points

Thanks for the input and additional info! Huge help.