Friday, 18 May 2018

Java - String charAt Example - How to get first and last characters

The charAt(int index) method of java.lang.String class can be used to retrieve a character from given index. The method returns a character, you can see its return type is char. The index starts from zero and ranges to length() - 1 where length() return the length of String. It's similar to an array where the first element is stored at zeroth index and the last element is stored at length -1 index because String is nothing but backed by a character array. If the value of the index is invalid i.e. it's lower than zero or negative or higher than length - 1 then this method throws an IndexOutOfBoundsException. In this article, I'll show you a couple of example of how to use the charAt() method to retrieve a character from String in Java.

1. chartAt() example with valid index

If you want to get a character or letter from the 4th position in given String you can call the charAt() method as below:

char fourth = "Avengers".charAt(3); // position 3 holds 4th character

Similarly to retrieve the 5th character you can pass 4 to the charAt method as shown below:

char fifth = "Avengers".chartAt(4);

Above code will return 5th character from the String.

For example, if sample String is "Avengers" then charAt(3) will return letter "n", the fourth character and charAt(4) will return letter "g", the fifth character.

2. Getting First Character from String

If you want the first letter from a given String then just call the charAt(0) because the first character stays at the zeroth position in String. For example, if given String is "Avenger" then charAt(0) will return letter "A", the first letter as shown below:

char first = "Avengers".charAt(0);


You can see the output is letter A, the first character from the given String "Avengers".

3. Getting the Last Character from String

If you want to retrieve the last character from String then you can call charAt(length -1) where length is the length of given String. For example, if given String is "Avengers" then "Avengers".charAt(7) will return letter "s" the last letter, which is from the seventh position because the length of String is 8.

String sample = "Avengers";
String last = sample.charAt(sample.length() -1);


You can see that the last character returned is the letter "s", which is from the 7th position.

Oracle Java Tutorials and Materials, Oracle Java Learning, Java Study Materials, Java String

4. charAt() example with an invalid index

If you call the charAt() method with the invalid index e.g. negative index or index greater than or equal to length then you will get IndexOutOfBoundException.

Following code will throw IndexOufOfBoundsException, you can just copy and run this in your Eclipse or IntelliJ IDEA code and see the output:

"Avengers".charAt(8); // index equal to length of String
"Avengers".charAt(-1) // negative index
"Avengers".charAt(9); // index greter than length of String

5. Complete Java Program

If you want to play with this method, here is some sample code to start with. You can change the String or change the index to figure out how to use charAt() method, what does it returns and when it throws an error:

package tool;

 * A simple Java Program to demonstrate how to use charAt() method of String 
 * class to retrieve first and last character.

public class Hello {

  public static void main(String[] args) {

    // sample String
    String sample = "Avengers";

    // Retrieve first character from String
    char firstLetter = sample.charAt(0);

    System.out.println("first letter from String: " + sample + " is : "
                                + firstLetter);

    // Retrieving last character from String
    char lastLetter = sample.charAt(0);
    System.out.println("last letter of String: " + sample + " is : "
                                 + lastLetter);

    // invalid index will throw IndexOutOfBoundsException


the first letter from String: Avengers is: A
last letter of String: Avengers is: A

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(
at tool.Hello.main(

You can see that StringIndexOutOfBoundsException, which is like ArrayIndexOutOfBoundException a subclass of IndexOutOfBoundsException is thrown because of an invalid index.

If you are not familiar with Errors and Exception in Java. It's very fundamental concept and a good knowledge of them it is required to write robust production quality Java code.

Oracle Java Tutorials and Materials, Oracle Java Learning, Java Study Materials, Java String

6. Important Points

Now that you know what does charAt(int index) function do and how it works, let's revise some important points:

1) The charAt() function is defined in the java.lang.String class

2) The charAt() function accepts an integer which is the index of character you want to retrieve from String.

3) If an index is invalid i.e. less than zero and higher than the length of String - 1 then it throws IndexOutOfBoundsException.

4) You can pass index zero if you want first character and length() - 1 to retrieve the last character.

5) To get all the character in the array, use the toCharArray() and to retrieve, a stream of characters from String in Java 8, just use the chars() method, which is only available since Java 8 in String class. 

6) Instead of retrieving a character from a position if you want opposite i.e. to know the position of a given character then you can use the indexOf(char letter) and lastIndexOf(char letter) method which returns the position of given character or -1 if given character is not found in String.

That's all about how to use the charAt() function from String class in Java. As explained in this article, the charAt() method can be used to retrieve an individual character from given String. You just need to pass the valid index. For example, if you want the first character from String then just call String.charAt(0) because index starts at zero in String.

Related Posts