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?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Jesse Luke Orange
  • 1,949
  • 3
  • 29
  • 71

2 Answers2

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.

Aleksandr Dubinsky
  • 22,436
  • 15
  • 82
  • 99
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.

Tal Malaki
  • 422
  • 5
  • 18
  • 3
    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) – Aleksandr Dubinsky Dec 29 '13 at 12:53