Sobes.tech
Junior — Middle

Can you explain what the CharSequence interface in Java is?

sobes.tech AI

Answer from AI

The CharSequence interface in Java represents an abstraction for a sequence of characters. It defines basic methods for working with text data, such as:

  • length() — returns the length of the sequence;
  • charAt(int index) — returns the character at the specified index;
  • subSequence(int start, int end) — returns a new CharSequence that is a subsequence of this sequence;
  • toString() — returns a string containing the characters in this sequence.

Classes like String, StringBuilder, StringBuffer, etc., implement this interface, allowing them to be used interchangeably in methods working with text.

Example usage:

public void printChars(CharSequence seq) {
    for (int i = 0; i < seq.length(); i++) {
        System.out.print(seq.charAt(i) + " ");
    }
}

printChars("Hello"); // String
printChars(new StringBuilder("World")); // StringBuilder