Extract a character from a string


Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

In this article, I tried to use the String#charAt() method. This method is used when you want to extract a single character at a specific position from a String type object. As a sample, I wrote a program to extract one character at a time from the beginning. However, this time I intentionally created a sample that causes an error, and listed some common mistakes.

Source and execution results

The flow is described below. However, it contains errors.

  1. Define a variable s of type String and initialize it with the string "Hello World.".
  2. Output "ENTIRE:" + s. (Use the println() method.)
  3. The following process is repeated until the repetition counter i is less than or equal to s.length() from 0.
    1. Output (i + 1) + “:" + s.charAt(i) with println.

The following are the source and execution results.

public class HelloCharAt {
	public static void main(String[] args) {
		String s = "Hello World.";

		System.out.println("entire:" + s);

		for (int i = 0; i <= s.length(); i++) {
			System.out.println((i + 1) + ":" + s.charAt(i));
Execution results
entire:Hello World.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12
	at java.lang.String.charAt(String.java:658)
	at source0001.HelloCharAt.main(HelloCharAt.java:10)


An error occurred when the value of the iteration counter i in the for statement was 12; StringIndexOutOfBoundsException was thrown, which is caused by the argument being out of range. Strings are numbered starting from the first character as 0, 1, 2… and so on. The reference book I have also states that the first character is 0. I was a little curious, so I quoted the API specification below.

Modifier and Type
Method and Description
Returns the char value at the specified index.

The name of the argument is index, and the description says “char value of the index", so I guess it is the same as an array. I was more curious about what the charAt method does internally, so I used the Eclipse shortcut keys to find out.

Place the cursor on charAt in the source code and press F3 key to go to the definition. (Note that I am using a Windows PC, Eclipse, and Java-SE1.8 compiler).

You should see the following source code.

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

A variable named value appears in the condition that throws StringIndexOutOfBoundsException. This value is an array of fields owned by the Strign class. This variable seems to contain the string held by the String object.

From the conditional expression, it can be read that an error will occur if the length of the string is entered in the argument of the charAt() method. The argument index is directly specified as the element number of the array in the retun statement. Now I am convinced that the beginning of the string should be specified with the number 0.

Another thing I noticed is that the length() method simply returns value.length, which means that if index is greater than or equal to the length of the string, an error will occur.

That’s all. I hope this is helpful to you.

Articles next and previous in the same category