Tanisha Vats Tanisha Vats - 14 days ago 8
Java Question

Java-Storing characters of a string in an array

for (int j = 0; j <= l - 1; j++)
{ char c1 = str.charAt(j);
n[j] = c1;
}
//It is showing error-arrayIndexoutofbounds


'str' is an inputted string and 'l' is the length of the string str.
I have to store all its character in an array and the array 'n' is of char type
I have tried to store it by for loop but its showing error . Please help me out.

Answer

Your array n should be declared as:

char[] n = new char[str.length()];

That creates an array with the exact size needed to put all your String's characters in it.

An ArrayIndexOutOfBoundsException is thrown when you access an illegal index of the array, in this case I suspect your array is smaller than the length of the String.