March 25, 2022

Java String charAt() Method

If you want to get specific character of the String by index you can use charAt() method of the String class in Java.

charAt() method

  • char charAt(int index)- Returns the char value at the specified index. For a String of length n the passed index should be with in the range 0 to n-1. Method throws IndexOutOfBoundsException if the index argument is negative or not less than the length of this string.

Java String charAt() method examples

1. Using charAt() to get the first and last characters of the String.

public class StringCase {
  public static void main(String[] args) {
    String str = "Hello World";
    // getting first character
    char firstChar = str.charAt(0);
    // getting last character
    char lastChar = str.charAt(str.length()-1);
    System.out.println("First character- " + firstChar);
    System.out.println("Last character- " + lastChar);
  }
}
Output
First character- H
Last character- d

Since index starts at 0 so first character is retrieved using the index 0. For getting the last character of the String, length() method of the String class is used to get the length of the String.

2. Getting all the characters of the String by iterating the String and retrieving each character using charAt() method.

public class StringCase {
  public static void main(String[] args) {
    String str = "Hello World";
    for(int i = 0; i < str.length(); i++) {
      System.out.println(str.charAt(i));
    }
  }
}
Output
H
e
l
l
o
 
W
o
r
l
d

3. If any index outside the range of the String is used that results in IndexOutOfBoundsException.

public class StringCase {
  public static void main(String[] args) {
    String str = "Hello World";
    System.out.println(str.charAt(20));
  }
}
Output
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:44)
	at java.base/java.lang.String.charAt(String.java:692)
	at com.knpcode.proj.Programs.String.StringCase.main(StringCase.java:7)

That's all for the topic Java String charAt() Method. If something is missing or you have something to share about the topic please write a comment.
You may also like

No comments:

Post a Comment