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
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework