//What's the error in the following code? I am not able to identify it shows the index 0 out of bounds exception.
public class stringBuilders{
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Shubham");
StringBuilder str2= new StringBuilder();
int j=0;
for(int i = str.length()-1; i>=0 ; i--)
{
str2.setCharAt(j ,str.charAt(i));
}
System.out.print(str2);
}
}
CodePudding user response:
As you are already iterating from end to start you can just append the characters to the fresh and empty string builder. setChar()
is only intended to replace existing characters.
public class StringBuilders {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("Shubham");
StringBuilder str2 = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
str2.append(str.charAt(i));
}
System.out.println(str2.toString());
}
}
gives
$ java StringBuilders.java
mahbuhS
CodePudding user response:
You haven't declared a value to the str2 string.
The for loop is trying to find a character at index j=0 in str2 to set value i of str2, which it cannot find.
Hence the error.
For this to work, you need declare a value of str2 to a length >= str1. i.e., if str1 = "0123456", str2 should be at least "0123456" or more.
Instead of using StringBuilder to set the char, you can use Strings to just add to it.
String str1 = new String("Shubham");
String str2 = new String();
int iter = str1.length() -1;
for(int i=iter; i>=0; i--) {
str2 = str2 str1.charAt(i);
}
System.out.println(str2)