Java String charAt() method with example

The Java String charAt() method returns the character at the specified index. The index value should lie between 0 and length()-1.
Signature:

 public char charAt(int index)  

Parameter:

 index- Index of the character to be returned.

Return:

 returns character at the specified position.

Exception:

 StringIndexOutOfBoundsException- If index is 
 negative or greater then the length of the 
 String.

Example:To show working of charAt() method



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// working of charAt() method
  
class Gfg {
    public static void main(String args[])
    {
        String s = "Welcome! to Geeksforgeeks Planet";
  
        char ch = s.charAt(3);
        System.out.println(ch);
  
        ch = s.charAt(0);
        System.out.println(ch);
    }
}

chevron_right


Output:

c
W
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// working of charAt() method
  
class Gfg {
    public static void main(String args[])
    {
        String s = "abc";
  
        char ch = s.charAt(4);
        System.out.println(ch);
    }
}

chevron_right


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.String.charAt(String.java:658)
    at Gfg.main(File.java:9)



String Class in Java

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.