Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java String: charAT() Method

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.

Pictorial presentation of Java String charAT() Method

Java String: charAT() Method

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:

Previous:Java String Methods
Next:codePointAt Method