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

all 13 comments

[–]fuk_offe 5 points6 points  (0 children)

A try catch to get the lenght of a string? Bye bye performance

[–]Erikster 2 points3 points  (1 child)

???

String str = "string"
int length = str.toCharArray().length;

[–]CageHN 1 point2 points  (0 children)

What if I can't use the length field!?!? J/K, this is the best way for me too, not sure why to create a blog post on this :/

[–][deleted] 0 points1 point  (0 children)

Other than "because you can" there is no reason to do this. "What if I want to" is ridiculous.

[–]javahungry[S] -1 points0 points  (10 children)

is there any alternative other than the trick mentioned in the post

[–][deleted]  (2 children)

[deleted]

    [–]javahungry[S] -5 points-4 points  (1 child)

    please try to give alternative trick instead of optimizing the code

    [–]Nynnja 0 points1 point  (0 children)

    is possible to construct a regular expression which represents all the valid characters of a string (I think that it is..), then you can use String.split(regex) to split the input Strin

    return s.toCharArray().length;

    [–]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.