4
String str[] = new String[5];
CSVReader read = new CSVReader(new FileReader("abc.csv"));
str = read.readNext();
str[3] = "A";

In the above code snippet, I am declaring array of strings of size 5. I am using OpenCSV to parse my CSV file. The CSV file has three columns. The statement str = read.readNext() stores values in str[0], str[1], str[2]. The problem is that after this statement is executed, the size of the array str is reduced to 3. Due to this str[3] throws ArrayIndexOutOfBounds exception. Why the size is reduced to 3 from 5 ?

1
  • 1
    "The statement str = read.readNext() stores values in str[0], str[1], str[2]." No it doesn't. It replaces str with an entirely new array. Commented May 12, 2016 at 15:58

4 Answers 4

6

The size of an array can NOT be changed, but read.readNext is returning a brand new array with probably a different size in which you assigning it to the same variable str.

Sign up to request clarification or add additional context in comments.

Comments

1

readNext is returing a whole new array for you:

String str[] = new String[5];

Means "Make 'str' refer to a new String array of length 5"

CSVReader read = new CSVReader(new FileReader("abc.csv"));

Make a new CSVReader called 'read'

str = read.readNext();

call 'readNext' and set 'str' to refer to the result (even though I just asked you to use that name to refer to a new, empty, String array of length 5)

str[3] = "A";

Now access the 4th element from the readNext result.

Incidentally, because you didn't create the array that 'str' refers to, you don't know its size, so using .length on it is required.

Comments

0

readNext() returns a reference to a String[]-array with the size of the columns in the csv and you store this in str.

After that, str refers to this String-array. You redeclare it.

Comments

0

You're not reading into the array but you assign a new object to str variable.

The compiler will complain if you define the str variable as final. Which is by the way a good practice to do. With final you express, that you do not intend to change the object reference and the compiler will help you enforce this so that you can not accidentally reassign the variable.

The original array is not resized as arrays are immutable (regarding dimensions). What happens after read.readNext() is the original arrays (size = 5) is no longer referenced and will be garbage collected. But until it is collected it still will be of size 5 (though that becomes somewhat irrelevant at that point).

1 Comment

It's not redeclaring the variable. It's assigning a new value to the variable. That's very different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.