w3resource

Java String: charAT() Method

charAt() method - Gets a particular character in a string

The charAT() method is used to get the character value at the specified index  in a string.

An index ranges from 0 to length() - 1.

As with array indexing, the first character value of the sequence is at index 0, the next at index 1, and so on.

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

Visual presentation of Java String charAT() Method

Java String: charAT() Method

Java Platform: Java SE 8 and above

Syntax charAT() method

charAt(int index)

Parameters charAT() method

Name Description Type
index The index of the character value. int

Return Value charAT() method

  • The character 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:

Previous:Java String Methods
Next:codePointAt Method



Follow us on Facebook and Twitter for latest update.