3
    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. Just remove that equal to sign in ur loop it will only be less than

Community
  • 1
  • 1
Tanz
  • 41
  • 1
  • 1
  • 8

3 Answers3

5

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.

f1sh
  • 11,489
  • 3
  • 25
  • 51
  • 1
    Or, alternatively, `char[] n = new char[l]`. (<- that's a lower-case `L`, not the digit "one") – Thomas Nov 24 '16 at 14:49
  • 3
    **Please note**: Strings in Java are UTF-16 Unicode. Because Unicode contains more than 65536 characters, this means some characters require 2 16-bit symbols to encode. For this reason, Oracle [recommends against](https://docs.oracle.com/javase/tutorial/i18n/text/design.html) using `char` types to represent character arrays (yes it's too bad but Unicode outgrew 16-bit only after Java already had comitted to it). Instead, make an array of `int` and use `codePointAt` and `codePointCount` etc. – Stijn de Witt Nov 24 '16 at 23:24
4

No need to create and fill such an array manually, there is a built-in method String.toCharArray that does the job for you:

n = str.toCharArray()
Thomas
  • 17,016
  • 4
  • 46
  • 70
  • No worries. You can replace the whole for-loop with the one line from my answer - it does the same thing. – Thomas Nov 24 '16 at 14:53
  • how can I post the full code it has some other errors also(not syntax) that I want to get clear – Tanz Nov 24 '16 at 15:05
  • You can edit your original question by clicking on "edit" (right under your question), but perhaps consider just writing a new question if you have other issues. – Thomas Nov 24 '16 at 15:11
2

If you want to convert string into character array then string class already have method called toCharArray().

String str = "StackOverflow";
char[] charArray = str.toCharArray();

then if you want to check content of array print it.

for(int i = 0;i < charArray.length ; i++) {
     System.out.print(" " + charArray[i]);
}
swapnil
  • 230
  • 3
  • 6