Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
What Is the Java String.charAt() Method?
The String.charAt() method returns the character at a specific index within a string. In Java, string indices are zero‑based, ranging from 0 to length() - 1.
Method Signature
public char charAt(int index)
Parameter
index – a single int value specifying the position of the desired character.
Return Value
Returns the character (type char) located at the given index.
Exceptions
Throws StringIndexOutOfBoundsException if index is negative or greater than or equal to the string’s length.
Practical Example
public class CharAtExample {
public static void main(String[] args) {
String s = "This is String CharAt Method";
// Character at index 0
System.out.println("Character at 0 position is: " + s.charAt(0));
// Character at index 5
System.out.println("Character at 5th position is: " + s.charAt(5));
// Character at index 22
System.out.println("Character at 22nd position is: " + s.charAt(22));
// Attempt to access an invalid index
char invalid = s.charAt(-1);
System.out.println("Character at -1 position is: " + invalid);
}
}
Output:
Character at 0 position is: T
Character at 5th position is: i
Character at 22nd position is: M
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Key points to remember:
- Only an
intargument is accepted. - The method returns a
charcorresponding to the provided index. - Indices outside the valid range trigger a
StringIndexOutOfBoundsException. - Always ensure
0 <= index < s.length()before callingcharAt().
Java
- Encapsulation in Java: A Comprehensive Guide with Practical Example
- Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java String.indexOf(): Locating Substrings & Practical Examples
- Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
- Java String.contains() Method: How to Check for Substrings – Practical Examples
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Polymorphism in Java: A Comprehensive Guide with Practical Examples
- Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
- Mastering Java's split() Method: A Practical Guide with Code Examples