DEV Community

Edwin Torres
Edwin Torres

Posted on • Edited on

3 2

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)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.