public class UsingArrayGetEvenLettersFromString {
public static void main(String[] args) {
// even letters
String str = new String("hello");
char[] ch = str.toCharArray();
char[] eCh = {};
char[] oCh = {};
System.out.println("length :"+ch.length);
for(int i=0; i<ch.length; i++) {
if(ch[i]%2 == 0) {
eCh[i] = ch[i];
}
else {
oCh[i] = ch[i];
}
}
for (char c : eCh) {
System.out.println(c);
}
for (char c : oCh) {
System.out.println(c);
}
}
}
Error: length :5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Strings.UsingArrayGetEvenLettersFromString.main(UsingArrayGetEvenLettersFromString.java:15)
I do not get what it does mean as far as I know … please suggest
>Solution :
Because when you make array you can’t change its size, and when you make array like this
char[] eCh = {};
it takes its length as zero.
You must give the array length first like this
char[] eCh = new char[str.length()];
char[] oCh = new char[str.length()];
Then you can use it normally.