0

Is there a difference in the size of character constant 'P' and a string containing a single character, say , "P" ? I understand both should be 2 Bytes. Am I right? Is there any way of checking this through code in Java (like the sizeof operator in C)? TIA

sumiK
  • 1
  • 2
  • Yes. A `String` also has an `int` indicating the `length`. A character is thus *smaller*. Additionally, a `char` is a primitive type, while `String` is a *reference type* (so it's also an `Object`). – Elliott Frisch Jan 25 '16 at 04:49
  • Go through these links : 1) http://stackoverflow.com/questions/10430043/difference-between-char-and-string-in-java 2) http://stackoverflow.com/questions/18925161/char-vs-string-in-java – Mananpreet Singh Jan 25 '16 at 04:53

1 Answers1

0

char is two bytes. A String is an Object and therefore its size is really implementation-dependent. A typical implementation includes at least:

  • the reference to the object itself (not a part of the object itself, but you can't have an object without at least one reference) which is either a pointer (32 or 64 bits) or a compressed pointer, which could be smaller;
  • the reference to the array containing the string, and that's another pointer or a compressed pointer;
  • the size of the array, of type int, that's 4 more bytes;
  • the array itself, which has the size 2 (in bytes);
  • whatever else the base class (Object) contains, usually it has no explicit fields, but may have "hidden" native implementation data.

So on a 32-bit system that will be 4+4+4+2=14 bytes, adding possible alignment effects, I'd guess it'll be at least 16 bytes. On a 64-bit system with efficiently compressed pointers and small enough heap it'll probably be the same.

Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73