How-To: Java charAt() String Function

ยท

2 min read

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

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

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

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 value of the function to the char variable c:

char c = s.charAt(4);

Finally we output c:

System.out.println(c);  // q

Here is the 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

  }
}

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.

ย