Search code examples
javastringjavadoctime-complexity

How String.charAt(int i) is implemented in Java?


If I want to check every char in a String using String.charAt(int i), would it count from start every time or it is converted to an array automatically and get the charAt index directly?

Would it be more efficient if I create a char array by String.toCharArray() and then go through the array by index?

Can I check this up in JavaDoc? Where?


Solution

  • The JRE is mostly open source. You can download a zip file here or browse online with websites like grepcode.

    String.charAt:

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