Java String.charAt()

The method charAt() returns the character at the specified index. The
index value must be between 0 and String.length() – 1.

Available Signatures

public char charAt(int index)

Example

@Test
public void whenCallCharAt_thenCorrect() {
    assertEquals('P', "Paul".charAt(0));
}

Throws

  • IndexOutOfBoundsException – if a non-existent or a negative index is
    passed to the method

@Test(expected = IndexOutOfBoundsException.class)
public void whenCharAtOnNonExistingIndex_thenIndexOutOfBoundsExceptionThrown() {
    int character = "Paul".charAt(4);
}

Leave a Reply

Your email address will not be published.