Matthew Holmes
Matthew Holmes

Reputation: 11

What is the purpose of the char datatype?

I am currently reading a textbook on Java and each chapter involving the String datatype also discusses char. My question is, what purpose does char have in the real world?

The only thing I have found is that because String is immutable, it makes it a poor choice for passwords. Thus, one should choose a character array (char[]) over String. However, Java does have a mutable class for strings called StringBuilder; would that not be just as suitable a replacement for strings as is char[]?

Upvotes: 0

Views: 170

Answers (1)

Tim B
Tim B

Reputation: 41188

This has already been answered in the comments really :)

A String is a collection of Chars. Without Chars you would have nothing to build Strings from.

Because Char[] and dealing with Char[] is so important they warrant having their own class to handle the processing of them - hence String.

In your coding you are unlikely to use the Char datatype directly unless you are processing Strings or handling passwords. The only reason Char[] is used for passwords is because it's harder to accidentally print them into logs/view them in memory/put them into string caches, etc and because once you have finished with it you can explicitly zero the elements in the Array so it never stays in memory longer than needed.

Upvotes: 2

Related Questions