The reason why it's saying index out of bounds is because you're going beyond the last index of the string, remember we always start counting at 0, so in this case, you meant to say
i < S.length()
.
for(i=0;i<=S.length();i++) // this is why it's saying index out of bounds because you're going 1 index beyond the last.
{
char ch=S.charAt(i);
y=ch+y;
}
The below solution should solve your "IndexOutOfBounds" problem:
for(i=0;i< S.length();i++) // notice the "i < S.length() "
{
char ch=S.charAt(i);
y=ch+y;
}
Also, I would like to provide a simple and easy algorithm which you can use to achieve the same result.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter string ");
String value = scanner.nextLine();
StringBuilder builder = new StringBuilder(value); // mutable string
System.out.println("reversed value: " + builder.reverse()); // output result
}
UPDATE
As you have asked me to expand on the issue of why you're getting IndexOutOfBounds error I will provide a demonstration below.
lets assume we have a variable String var = "Hello";
now as you can see there are 5 characters within the variable, however, we start counting at 0, not 1 so "H" is index 0, "e" is index 1, "l" index 2 and so forth, eventually if you want to access the last element it's index 4 even though we have 5 characters within the string variable. So referring to your question the reason why it says index of out bounds is because you're going 1 index above the last. here is a link for further explanation and exercises on the issue.