Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String array size gets modified

Tags:

java

arrays

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 ?

like image 722
Harish R Avatar asked Mar 12 '23 08:03

Harish R


2 Answers

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.

like image 188
Sleiman Jneidi Avatar answered Mar 28 '23 01:03

Sleiman Jneidi


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.

like image 40
daveb Avatar answered Mar 28 '23 00:03

daveb