The Wayback Machine - https://web.archive.org/web/20230403061131/https://www.geeksforgeeks.org/java-string-charat-method-example/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Java String charAt() method with example

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 15 Dec, 2022
Improve Article
Save Article
Like Article

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 than the length of the 
 String.

Example:To show working of charAt() method 

java




// 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);
    }
}

Output:

c
W

java




// 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);
    }
}

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


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!