0
public MyString1 substring(int begin, int end)
{
    char[] charset = new char[end - begin];
    
    while( begin < end)
    {
        charset[begin] = val[begin];
        begin++;
    }
    return new MyString1(charset);
}

When I try to test out this method in the main method it gives me "Index 2 out of bounds for length 2" error. The size of the array is 5 so how is it that 2 is out of bound?

I used this line to test it

char[] test1 = {'T', 'e', 'S', 't', '1'};
MyString1 s1 = new MyString1(test1);
System.out.println(s1.substring(1, 3));
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • What does the variable named s1 look like? And which line gives you that error? – Jhanzaib Humayun Mar 21 '22 at 10:58
  • You are trying to insert a character at position 2 in the original array (`val`) into position 2 of array `charset`, while `charset` has length 2 (valid positions are 0 and 1). You need to properly offset the position when inserting into the target array. Or better yet, use the `Arrays.copyOfRange` – Mark Rotteveel Mar 21 '22 at 11:18

0 Answers0