For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Accessing individual characters is a common task when working with strings in Java. The charAt() function in Java programming helps retrieve a character at a specific index within a string. It is crucial in string manipulation, validation, and character-based operations. Understanding how charAt() works, its syntax, examples, and common errors like StringIndexOutOfBoundsException is essential for writing efficient Java programs. This guide will cover all technical aspects of the charAt() in Java with examples.
Take your Java expertise to the next level — enroll in upGrad’s Software Engineering course now!
The charAt() method in Java returns the character located within a string's specified index. It’s zero-indexed, meaning the first character is at index 0, the second at index 1, and so on.
Key Points:
Syntax
char character = string.charAt(index);
Must read: Top 13 String Functions in Java | Java String [With Examples]
Parameters:
Returns:
Throws:
Step into the future of tech with these top-rated software engineering courses:
StringIndexOutOfBoundsException Error
The StringIndexOutOfBoundsException occurs when you try to access a character at an invalid index —
For example, using an index less than 0 or greater than or equal to the string’s length.Always validate the index or use try-catch blocks to avoid this error during runtime.
public class Main {
public static void main(String[] args) {
String str = "Hello";
try {
System.out.println(str.charAt(8)); // Invalid index
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Output:
Caught Exception: String index out of range: 8
Explanation:
In the above code, the string "Hello" has a length of 5 (indices 0–4).
Trying to access str.charAt(8) causes StringIndexOutOfBoundsException, as 8 is beyond the string’s limit.
The exception is caught and a meaningful message is printed instead of crashing the program.
Also read: Difference Between char and String in Java
Here are simple, real-world examples showing how charAt() in Java works:
public class Main {
public static void main(String[] args) {
String text = "Java";
char firstChar = text.charAt(0);
System.out.println(firstChar);
}
}
Output:
J
Explanation:
The code fetches the character at index 0 of "Java", which is 'J'. Indexing starts from 0 in Java strings.
Must check: String Length in Java
public class Main {
public static void main(String[] args) {
String word = "Programming";
char lastChar = word.charAt(word.length() - 1);
System.out.println(lastChar);
}
}
Output:
g
Explanation:
Using word.length() - 1 dynamically fetches the last character 'g' of "Programming", ensuring safe access.
Checkout: Comprehensive Guide to Exception Handling in Java: Best Practices and Examples
public class Main {
public static void main(String[] args) {
String str = "Code";
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
}
}
Output:
C
o
d
e
Explanation: The loop prints each character one by one. charAt(i) accesses the character at the current loop index.
Must Read: Char Array in Java
public class Main {
public static void main(String[] args) {
String data = "StackOverflow";
if (data.charAt(5) == 'O') {
System.out.println("Character at index 5 is O");
} else {
System.out.println("Different character found");
}
}
}
Output:
Character at index 5 is O
Explanation: The program checks if the character at index 5 of "StackOverflow" is 'O' and confirms it with a message.
Also read: Reverse String in Java
public class Main {
public static void main(String[] args) {
String message = "Hello";
try {
char ch = message.charAt(10); // Invalid index
System.out.println(ch);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Index is out of range!");
}
}
}
Output:
Index is out of range!
Explanation: Since "Hello" has only 5 characters (index 0–4), accessing index 10 throws an exception, which is caught and handled.
The charAt() method in Java is fundamental for any operation where character-level string processing is needed. Whether you are validating user inputs, parsing texts, or developing algorithms, mastering charAt() will greatly simplify your coding and avoid common pitfalls like invalid index errors.
The charAt() method retrieves the character located at a specific index in a string. Indexing starts from 0. If you provide a valid index, it returns the corresponding character; if the index is invalid, Java throws a StringIndexOutOfBoundsException.
If you pass a negative index to the charAt() method, Java throws a StringIndexOutOfBoundsException. This is because string indices must always be within the range from 0 to the length of the string minus one.
Yes, charAt() is commonly used inside a for loop to iterate over each character in a string. You can access each character by incrementing the index value from 0 up to the string’s length minus one.
Yes, Java uses zero-based indexing for strings. This means the first character of the string is at index 0, the second character at index 1, and so on until string.length() - 1.
The charAt() method throws a StringIndexOutOfBoundsException when you try to access a character at an index that is either negative or greater than or equal to the string’s length.
No, using charAt() on an empty string will immediately throw a StringIndexOutOfBoundsException, even if you try to access index 0, because an empty string has no characters to retrieve.
To avoid exceptions, always check that the index is greater than or equal to 0 and less than the string's length. You can use conditions like if (index >= 0 && index < string.length()) before calling charAt().
The charAt() method returns a char, which represents a single character, not a numeric value. However, since characters have Unicode values, you can cast the result to an integer to get its numeric representation.
The charAt() method returns a single character at a specified index, while substring() extracts a sequence of characters between a starting and ending index, returning a new string instead of a single character.
Yes, you can use charAt() inside a loop that runs backward (from last index to 0) to manually build a reversed version of the string by accessing each character one by one.
No, charAt() returns a char, not another String. Since a char is a primitive type, you cannot chain charAt() methods directly like you can with string methods. You must operate on the original string again.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.