Substring vs charAt in Java: Key Differences and Usage
substring extracts a part of a string as a new string, while charAt returns a single character at a specified index. Use substring when you need a string segment and charAt when you want just one character.Quick Comparison
This table summarizes the main differences between substring and charAt methods in Java.
| Aspect | substring | charAt |
|---|---|---|
| Return Type | String | char |
| Purpose | Extracts a substring from a string | Retrieves a single character from a string |
| Parameters | Start index, optional end index | Single index |
| Output Length | Variable length substring | Single character |
| Usage Example | str.substring(2,5) | str.charAt(3) |
| Throws Exception | IndexOutOfBoundsException if indexes invalid | IndexOutOfBoundsException if index invalid |
Key Differences
The substring method returns a new String that contains characters from the original string starting at the specified start index and optionally ending before the end index. It is useful when you want to extract a part of the string, like a word or phrase.
On the other hand, charAt returns a single char value at the specified index. It is used when you need to access or check one character, such as validating a character or iterating through characters.
Both methods throw IndexOutOfBoundsException if the given index or indexes are outside the string's range. Also, substring can create a new string object, which may have a slight performance cost compared to charAt that returns a primitive character.
substring Example
public class SubstringExample { public static void main(String[] args) { String text = "Hello World"; String part = text.substring(0, 5); // Extracts "Hello" System.out.println(part); } }
charAt Equivalent
public class CharAtExample { public static void main(String[] args) { String text = "Hello World"; char ch = text.charAt(0); // Gets 'H' System.out.println(ch); } }
When to Use Which
Choose substring when you need a part of the string as a new string, such as extracting words or phrases. Use charAt when you only need to access or check a single character, like in loops or condition checks. For example, parsing or validating characters is best done with charAt, while slicing strings is best done with substring.
Key Takeaways
substring returns a new string segment; charAt returns a single character.substring to extract parts of a string, and charAt to access individual characters.IndexOutOfBoundsException if indexes are invalid.charAt is more efficient for single character access.