Sama Willson wrote:I have attached a snippet of code from one of the mock tests.
Why do you post code snippets as screenshots and not the plain code snippets (and
you should of course
UseCodeTags )? If I want to compile (and execute) your code snippets, I know have to type them myself. So I'll be losing precious time which I could otherwise be spending on typing a nice reply... And another reason: attached images are not searchable using the search engine, plain text or a code snippet definitely is.
Sama Willson wrote:I am confused about line #5, it calls the insert method to add a char sequence at str.length(21) which is last index +1, when the index ends at 20. Why does it not throw an exception since the index is out of bounds? Please help me understand this.
According to the
javadoc of the (overloaded)
insert() method of the
StringBuilder class, the
offset argument must be greater than or equal to 0, and less than or equal to the length of the sequence itself. So the length of the
StringBuilder object is a valid offset for the
insert() method and that's why no exception is thrown at runtime.
If you are using the length of the
StringBuilder object as the offset, you are inserting the value at the end of the char sequence. So you are actually appending the value
That's why these two code snippets are functionally equivalent
Hope it helps!
Kind regards,
Roel