0
0
JavaComparisonBeginner · 3 min read

Char vs String in Java: Key Differences and Usage Guide

In Java, char is a single 16-bit Unicode character, while String is a sequence of characters used to represent text. char holds one character value, but String can hold many characters and offers many methods for text manipulation.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of char and String in Java.

AspectcharString
TypePrimitive data typeClass (reference type)
Size2 bytes (16 bits)Variable (depends on length)
ValueSingle Unicode characterSequence of characters
MutabilityImmutable (single value)Immutable (object content cannot change)
Default value'\u0000' (null character)null
Common useStore one characterStore text or multiple characters
⚖️

Key Differences

char is a primitive type that stores exactly one character using 16 bits, representing Unicode characters. It is simple and efficient for single character storage and operations.

On the other hand, String is a class that represents a sequence of characters. It can hold zero or more characters and provides many built-in methods for text processing like concatenation, searching, and substring extraction.

While char variables hold a single character value directly, String variables hold references to objects in memory. Both are immutable, meaning their values cannot be changed after creation, but String offers more flexibility for working with text data.

⚖️

Code Comparison

This example shows how to store and print a single character using char.

java
public class CharExample {
    public static void main(String[] args) {
        char letter = 'A';
        System.out.println("Char value: " + letter);
    }
}
Output
Char value: A
↔️

String Equivalent

This example shows how to store and print a single character using a String object.

java
public class StringExample {
    public static void main(String[] args) {
        String letter = "A";
        System.out.println("String value: " + letter);
    }
}
Output
String value: A
🎯

When to Use Which

Choose char when you need to store or manipulate a single character efficiently, such as reading characters one by one or working with character arrays.

Choose String when you need to work with text, multiple characters, or require string operations like concatenation, searching, or formatting.

In general, use String for most text-related tasks and char for low-level character handling.

Key Takeaways

char stores a single Unicode character as a primitive type.
String stores sequences of characters as immutable objects.
Use char for single characters and String for text and multiple characters.
String provides many useful methods for text manipulation.
Both char and String are immutable in Java.