What is the difference between char and String in Java, and when would you choose each one?
A char holds a single character. A String holds a sequence of characters, and it can hold none of them at all.
They are not really the same kind of thing. A char is a primitive value, so it is a number underneath, it can never be null, and it takes up a fixed amount of memory. A String is an object on the heap, so it can be null, it has methods on it, and its memory depends on how much text it holds.
There are three differences that matter in practice.
The first one is the size. A char always holds exactly one character. A String holds any number of them, including none.
The second one is the null question. A char can never be null. A String can be, and that is where most of the NullPointerException errors in Java come from.
The third one is what they can do. A char can be added to a number, because it is a number. A String has a large set of methods that a character does not have, such as substring, split and toUpperCase.
public class Main {
public static void main(String[] args) {
char letter = 'x';
String text = "x";
System.out.println("char size : " + 1);
System.out.println("string length: " + text.length());
System.out.println("char is a number : " + (int) letter);
// A char can be null. A String can be.
char notNull = 'a';
String maybeNull = null;
System.out.println("char : " + notNull);
System.out.println("string null : " + maybeNull);
}
}
So when do you choose each one? Use a char when you are dealing with one character as part of a calculation, such as working out the letter that comes after another one, or when you are reading characters one at a time out of a stream. Use a String for everything else, because text is text and a String is what the standard library works with.
One detail is worth knowing. A char holds one UTF-16 code unit, so a character outside the basic multilingual plane needs two of them. That is why the character counting methods on a String can give a different answer from length. The methods codePointCount and the code point APIs give you the answer that counts real characters.
The next question in this topic looks at how to compare the two safely.