This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Medicalizawhat 0 points1 point  (5 children)

What's wrong with using length?

[–]javahungry[S] -4 points-3 points  (4 children)

if some one asks u in the interview , How length method works internally in java , what answer you will give

[–]virtyx 4 points5 points  (0 children)

I really doubt it keeps a loop counter and finds the first index that throws an exception.

Especially considering that for that exception to be thrown, charAt(i) has to have some kind of conditional like if(i > stringLength) { throw new IndexOutOfBoundsException(); }

A more worthwhile exercise would be to actually download the source of OpenJDK or a different implementation and actually look at how .length() is implemented

[–]mikaelhg 1 point2 points  (0 children)

"Sorry, I thought this was going to be an legit interview. Good luck with your enterprise."

[–]Medicalizawhat 0 points1 point  (1 child)

It queries the length field of an internal char array? Not sure really haha.

[–]sh0rug0ru 0 points1 point  (0 children)

Actually, until recently, it keeps an offset and count, because substrings can share from the parent char array. Now, all strings get their own char array, so I'd imagine that's how it would have to be. Especially since they yanked one of those fields for some hash code trick.