Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download PDF

How to get First and Last Character of String in Java? charAt Example

Hello Java programmers, if you are wondering how to get the first and last characters from a given String then you have come to the right place. In this Java tutorial, I will show you how you can use charAt() method from the String class to retrieve characters from String for any given index. The charAt(int index) method of the java.lang.String class can be used to retrieve a character from a 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() returns 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 examples 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 a 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);

The above code will return the 5th character from the String.

For example, if sample String is "Avengers" then charAt(3) will return the letter "n", the fourth character, and charAt(4) will return the letter "g", the fifth character. You can further see these free Java programming courses to learn more about String and characters in Java. 



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 the letter "A", the first letter as shown below:

char first = "Avengers".charAt(0);
System.out.println(first)

Output
A

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 a given String. For example, if the given String is "Avengers" then "Avengers".charAt(7) will return letter "s" to 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);

System.out.println(last);
Output
s
You can see that the last character returned is the letter "s", which is from the 7th position. If you want to learn more about different String methods like length etc, See these best Java Programming courses from the internet to learn more about chartAt function and String API in Java. 

3. Getting the Last Character from 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 greater than length of String


5. Complete Java Program to get First and Last Character from String

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(sample.length() - 1);
    System.out.println("last letter of String: " + sample + " is : "
                                 + lastLetter);

    // invalid index will throw IndexOutOfBoundsException
    sample.charAt(-1);
    sample.charAt(sample.length());

  }

}
Output:
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(String.java:658)
at tool.Hello.main(Hello.java:26)

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. I suggest you go through these Java Programming courses to learn them. It's a very fundamental concept and a good knowledge of them is required to write robust production quality Java code.

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



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 the first character and length() - 1 to retrieve the last character.

5. To get all the characters 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. You can further see The Complete Java Masterclass learn more about new methods added in JDK 8, 9, and 10 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 a given character or -1 if a given character is not found in String.

That's all about how to use the charAt() function from the String class in Java. As explained in this article, the charAt() method can be used to retrieve an individual character from a 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.

Further Learning
The String API Documentation (Java SE 10)

Thanks for reading this article. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

Lastly, what is your favorite Java programming exercise? Palindrom, Prime Number, Fibonacci series, Binary Search, or this one?  Do let me know in comments. 

2 comments:

  1. But the last letter in Avengers is not A. You repeated the code to get the first letter

    ReplyDelete
    Replies
    1. Yes, that was the bug, thanks for pointing it out.

      Delete

Feel free to comment, ask questions if you have any doubt.