w3resource logo


Introduction to Java Programming

Java String: charAT() Method

Secondary Nav

public char charAt(int index)

The charAT() method is used to get the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

If the char value specified by the index is a surrogate, the surrogate value is returned.

Java Platform: Java SE 8

Syntax :

charAt(int index)

Parameters:

Name Description Type
index the index of the char value. int

Return Value :
The char value at the specified index of this string. The first char value is at index 0.

Return Value Type: char

Throws: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

Example : Java String charAT() Method

public class Example {
public static void main(String[] args)
    {
        String str = "Python Exercises!";
System.out.println("Original String = " + str);
        // Get the character at positions 0 and 10.
int index1 = str.charAt(0);
int index2 = str.charAt(10);

        // Print out the results.
System.out.println("The character at position 0 is " +
            (char)index1);
System.out.println("The character at position 10 is " +
            (char)index2);
    }
}

Output:

Original String = Python Exercises!                    
The character at position 0 is P                       
The character at position 10 is r

Example of Throws: charAt(int index) Method

IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

Let

int index2 = str.charAt(-10);

in the above example.

Output:

Exception in thread "main" java.lang.StringIndexOutOfBo
undsException: String index out of range: -10          
        at java.lang.String.charAt(String.java:658)    
        at Exercise.main(Example.java:8) 

Java Code Editor:







Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program