Java string - compare charAt() and index operator []

character, indexing, java, string

Solution

The implementation of `String#charAt(int index)` for Oracle's Java 7:

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

It's a little safer with the check, but it's the exact same behavior.

It would actually be slower to return the `char[]`

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

since you have to copy it first.

Problem

I wonder whether it is slower to use .charAt() than convert the string variable `s` to char[] `a` array and access it via `a[i]` instead of `s.charAt(i)` ? Let's say we are working on problem that has lots of operator on each character within the string.

Original source

Related problems