You could consider this analogy:
You need one apple. Would you rather have one apple in your hand or a large box that could contain more apples, but should contain only one?
With the primitive char type, it is easier to work with the String class in situations where you need only one character. This is also much less overhead because the String class has many additional methods and information that it needs to store in order to be effective in processing multiple-character strings. Using the String class when you only need one character is basically redundant. If you want to read a variable of both types to get a character, this is the code that will do this:
// initialization of the variables char character = 'a'; String string = "a"; // writing a method that returns the character char getChar() { return character; // simple! } char getCharFromString() { return string.charAt(0); // complicated, could fail if there is no character }
If this code looks complicated, you can ignore it. The conclusion is that using String when you only need one character is excessive.
Basically, the String class is used when you need more than one character. You can also just create an array of char s, but then you would not have any useful methods of the String class, such as .equals() and .length() methods.
RaptorDotCpp
source share