0
0
JavaComparisonBeginner · 3 min read

Substring vs charAt in Java: Key Differences and Usage

In Java, 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.

AspectsubstringcharAt
Return TypeStringchar
PurposeExtracts a substring from a stringRetrieves a single character from a string
ParametersStart index, optional end indexSingle index
Output LengthVariable length substringSingle character
Usage Examplestr.substring(2,5)str.charAt(3)
Throws ExceptionIndexOutOfBoundsException if indexes invalidIndexOutOfBoundsException 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

java
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);
    }
}
Output
Hello
↔️

charAt Equivalent

java
public class CharAtExample {
    public static void main(String[] args) {
        String text = "Hello World";
        char ch = text.charAt(0); // Gets 'H'
        System.out.println(ch);
    }
}
Output
H
🎯

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.
Use substring to extract parts of a string, and charAt to access individual characters.
Both throw IndexOutOfBoundsException if indexes are invalid.
charAt is more efficient for single character access.
Choose based on whether you need a string or a character.