Reputation: 73
i made a program in which i have to find the reverse of the string .i found the following error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at mypackage.Reverse1.main(Reverse1.java:18)
following is my code
public static void main(String args[])
{
String s ="saima";
//first we cal length of string
int L= s.length();
//now i declchararry of given string length
char[] charArray = s.toCharArray();
// i decl new arry
char[] array=new char[L];
int j=L;
for(int k=0; k<L; k++)
{
array[k]= charArray[j];
j--;
}
String output1 = new String(array);
System.out.println("output1 : " + output1);
}
Upvotes: 0
Views: 55
Reputation: 155
public static void main(String args[])
{
String s ="saima";
System.out.println("output1 : " + new StringBuilder(s).reverse().toString());
}
Upvotes: 1
Reputation: 394156
In charArray[j]
, j is initially out of bounds, since you initialize it to the size of the String.
If you change
int j=L;
to
int j=L-1;
It will work.
Or you can get rid of the j
variable :
for(int k=0; k<L; k++)
{
array[k] = charArray[L-1-k];
}
Upvotes: 4