Java
Programming
String
CharSequence
Code Comparison

CharSequence VS String in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Java, understanding the distinction between CharSequence and String is pivotal for effective programming, particularly when dealing with text processing. Both play crucial roles but are utilized in slightly different contexts based on their capabilities and characteristics.

Understanding String

The String class in Java is one of the most frequently used data types. A String represents a sequence of characters and offers a multitude of methods to perform operations like substring, concatenation, and comparison. Strings in Java are immutable; once created, their values cannot be changed. This immutability makes String safe from modification, which is particularly useful in multithreaded environments.

Here is a simple example of creating and manipulating a string:

java
String str = "Hello, World!";
System.out.println(str.length()); // 13
System.out.println(str.substring(7)); // "World!"

Understanding CharSequence

On the other hand, CharSequence is an interface that represents a readable sequence of char values, much like String. It is implemented by several classes, including String, StringBuilder, StringBuffer, and CharBuffer, among others. The purpose of CharSequence is to provide a uniform, read-only access to many different kinds of char sequences. This abstraction allows methods to accept any kind of char sequences without being limited to just String objects.

Here’s an example where CharSequence is used:

java
CharSequence cs = "Example";
System.out.println(cs.length()); // 7
System.out.println(cs.charAt(3)); // 'm'

Comparing String and CharSequence

While String is a direct implementation, dealing with actual character data, CharSequence is a more flexible interface which various character sequence classes can implement. This allows methods interacting with text data to be more flexible and not tightly coupled to the String class.

For example, if a method only requires reading sequence and length of characters, parameters can be declared as CharSequence. This allows you to pass a String, StringBuilder, StringBuffer, or any other CharSequence implementation to the method without additional adaptations:

java
1public static int countVowels(CharSequence cs) {
2    int count = 0;
3    String vowels = "aeiouAEIOU";
4    for (int i = 0; i < cs.length(); i++) {
5        if (vowels.indexOf(cs.charAt(i)) != -1) {
6            count++;
7        }
8    }
9    return count;
10}
11
12String s = "Hello";
13StringBuilder sb = new StringBuilder("World");
14System.out.println(countVowels(s)); // 2
15System.out.println(countVowels(sb)); // 1

Table: Key Differences Between String and CharSequence

FeatureStringCharSequence
TypeClassInterface
ImmutabilityImmutableImplementation dependent
Implemented ByOnly itselfString, StringBuffer, StringBuilder, CharBuffer, etc.
Usage ContextFixed text manipulationFlexible reading of characters
Main MethodsComprehensive methods like equalsIgnoreCase, split, etc.Basic methods like length, charAt, subSequence

Conclusion

In summary, the use of String versus CharSequence depends largely on the specific requirements of your application. If you need a mutable sequence of characters, or you are dealing with specialized buffer implementations, CharSequence is preferable due to its versatility and adaptability. However, for standard text manipulation with immutability guarantees, String remains the optimal choice.

Understanding these differences enhances flexibility and efficiency in Java programming, particularly in applications where text processing is a fundamental component.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions