How do I get char value of a string at a specified position?

The chartAt() method of the String class returns the char value at the specified index. An index ranges from 0 to length() - 1. If we specified an index beyond of this range a StringIndexOutOfBoundsException exception will be thrown.

These method use zero based index which means the first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

package org.kodejava.lang;

public class CharAtExample {
    public static void main(String[] args) {
        String[] colors = {"black", "white", "brown", "green", "yellow", "blue"};

        for (String color : colors) {
            // Get char value of a string at index number 3. We'll get the 
            // fourth character of each color in the array because the 
            // index is zero based.
            char value = color.charAt(3);
            System.out.printf("The fourth char of %s is '%s'.%n", color, value);
        }

    }
}

Here is the program output:

The fourth char of black is 'c'
The fourth char of white is 't'
The fourth char of brown is 'w'
The fourth char of green is 'e'
The fourth char of yellow is 'l'
The fourth char of blue is 'e'
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.