How to Use the CharSequence Interface in Java - dummies

How to Use the CharSequence Interface in Java

By Doug Lowe

The Java API includes a useful interface called CharSequence. All three of these classes — String, StringBuilder, and StringBuffer — implement this interface. This method exists primarily to let you use String, StringBuilder, and StringBuffer interchangeably.

Toward that end, several of the methods of the String, StringBuilder, and StringBuffer classes use CharSequence as a parameter type. For those methods, you can pass a String, StringBuilder, or StringBuffer object. Note that a string literal is treated as a String object, so you can use a string literal anywhere a CharSequence is called for.

In case you’re interested, the CharSequence interface defines four methods:

  • char charAt(int): Returns the character at the specified position.
  • int length(): Returns the length of the sequence.
  • subSequence(int start, int end): Returns the substring indicated by the start and end parameters.
  • toString(): Returns a String representation of the sequence.

If you’re inclined to use CharSequence as a parameter type for a method so that the method works with a String, StringBuilder, or StringBuffer object, be advised that you can use only these four methods.