2

My question is related to Java but is quite general. When making such things as calculators I see people store the operator as a char as opposed to a string? Surely a string is easier to work with?

In said scenario are there any advantages of using char over string?

1
  • String uses a char[] instead of String Commented Dec 29, 2013 at 14:18

2 Answers 2

6

A char explicitly requires one character. It can't take two, nor zero, and not even a null. This increases type safety where this requirement is appropriate.

Also, using char is slightly faster than using String, in Java.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, Requirement is appropriate. So the answer is it depends.
5

Also, char class has special method to check if the char is a digit and so on. Char takes less memory than a string because char is a value type and not a reference type. The char value will seat on the stack instead of the heap. Meaning faster reading and writing - better performence.

1 Comment

Good point about those methods. A single-character String can also emulate them with matches() and an appropriate [Unicode character class (or other regular expression).](www.regular-expressions.info/unicode.html)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.