Java CharSequence Interface

Introduction

The CharSequence interface in Java represents a readable sequence of characters. It is implemented by several classes and provides a common way to handle different types of character sequences.

Table of Contents

  1. What is CharSequence?
  2. Key Methods
  3. Implementations
  4. Examples of CharSequence
  5. Conclusion

1. What is CharSequence?

CharSequence is an interface that defines methods for character sequences. It provides a way to handle strings, string builders, and other character sequences uniformly.

2. Key Methods

  • charAt(int index): Returns the character at the specified index.
  • length(): Returns the length of the sequence.
  • subSequence(int start, int end): Returns a new CharSequence that is a subsequence of this sequence.
  • toString(): Returns a String representation of the sequence.

3. Implementations

Common classes that implement CharSequence include:

  • String
  • StringBuilder
  • StringBuffer
  • CharBuffer

4. Examples of CharSequence

Example 1: Using CharSequence with String

This example demonstrates how to use CharSequence methods with a String.

public class CharSequenceStringExample {
    public static void main(String[] args) {
        CharSequence cs = "Hello, World!";

        System.out.println("Character at index 1: " + cs.charAt(1));
        System.out.println("Length: " + cs.length());
        System.out.println("Subsequence (0, 5): " + cs.subSequence(0, 5));
        System.out.println("String representation: " + cs.toString());
    }
}

Output:

Character at index 1: e
Length: 13
Subsequence (0, 5): Hello
String representation: Hello, World!

Example 2: Using CharSequence with StringBuilder

Here, we use CharSequence methods with a StringBuilder.

public class CharSequenceStringBuilderExample {
    public static void main(String[] args) {
        CharSequence cs = new StringBuilder("Hello, Java!");

        System.out.println("Character at index 6: " + cs.charAt(6));
        System.out.println("Length: " + cs.length());
        System.out.println("Subsequence (0, 5): " + cs.subSequence(0, 5));
        System.out.println("String representation: " + cs.toString());
    }
}

Output:

Character at index 6:  
Length: 12
Subsequence (0, 5): Hello
String representation: Hello, Java!

Conclusion

The CharSequence interface in Java provides a uniform way to handle different types of character sequences. It is implemented by several classes, allowing for flexible manipulation and representation of text data in Java applications.

Comments