DEV Community

Edwin Torres
Edwin Torres

Posted on • Updated on

How-To: Java charAt() String Function

A string is a sequence of characters. Sometimes we need to access one character in the string. The Java String function charAt() returns the character at a given position in a string, where positions start at 0.

Here is an example. First, we create a string in Java:

String s = "The quick brown fox jumped over the lazy dog.";
Enter fullscreen mode Exit fullscreen mode

The string value is this entire sentence: The quick brown fox jumped over the lazy dog. The variable s refers to the string. We use this variable to invoke String methods on the string.

Next, we invoke the charAt() method on the string variable s, passing the parameter 4. This function returns the char value at position 4. Since string indexes start at 0, the function returns character q. Note that a space is a character too. The code assigns the return valueq to the char variable c:

char c = s.charAt(4);
Enter fullscreen mode Exit fullscreen mode

Finally we output c:

System.out.println(c);  // q
Enter fullscreen mode Exit fullscreen mode

Here is a complete program:


public class Example {
  public static void main(String[] args) {

    String s = "The quick brown fox jumped over the lazy dog.";

    char c = s.charAt(4);
    System.out.println(c);  // q

  }
}
Enter fullscreen mode Exit fullscreen mode

Execute the program to see the output q in the terminal.

Note that s.charAt(0) returns the first character in the string: T.

Try the charAt() String function to retrieve other characters in the string.

Thanks for reading. 😃

Follow me on Twitter @realEdwinTorres for more programming tips and help.

Top comments (0)