Char vs String in Java: Key Differences and Usage Guide
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.
| Aspect | char | String |
|---|---|---|
| Type | Primitive data type | Class (reference type) |
| Size | 2 bytes (16 bits) | Variable (depends on length) |
| Value | Single Unicode character | Sequence of characters |
| Mutability | Immutable (single value) | Immutable (object content cannot change) |
| Default value | '\u0000' (null character) | null |
| Common use | Store one character | Store 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.
public class CharExample { public static void main(String[] args) { char letter = 'A'; System.out.println("Char value: " + letter); } }
String Equivalent
This example shows how to store and print a single character using a String object.
public class StringExample { public static void main(String[] args) { String letter = "A"; System.out.println("String value: " + letter); } }
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.char for single characters and String for text and multiple characters.String provides many useful methods for text manipulation.char and String are immutable in Java.