In one of my classes I have a field of type Character
. I preferred it over char
because sometimes the field has "no value" and null
seams to me the cleanest way to represent this (lack of) information.
However I'm wondering about the memory footprint of this approach. I'm dealing with hundred of thousands of objects and the negligible difference between the two options may now deserve some investigation.
My first bet is that a char
takes two bytes whereas a Character
is an object, and so it takes much more in order to support its life cycle. But I know boxed primitives like Integer
, Character
and so on are not ordinary classes (think about boxing and unboxing), so I wonder if the JVM can make some kind of optimization under the hood.
Furthermore, are Character
s garbage collected like the other stuff or have a different life cycle? Are they pooled from a shared repository? Is this standard or JVM implementation-dependent?
I wasn't able to find any clear information on the Internet about this issue. Can you point me to some information?
A variable of type char occupies two bytes in memory. The value of a char variable is a single character such as A, *, x, or a space character. The value can also be a special character such a tab or a carriage return or one of the many Unicode characters that come from different languages.
char is a primitive type that represents a single 16 bit Unicode character while Character is a wrapper class that allows us to use char primitive concept in OOP-kind of way. Thanks for your answer.
For a default encoding, it will take 1 byte for a character. So Answer is 1 byte for default encoding.
Definition and Usage The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.
If you are you using Character
to create character then prefer to use
Character.valueOf('c'); // it returns cached value for 'c'
Character c = new Character('c');// prefer to avoid
Following is an excerpt from javadoc.
If a new Character instance is not required, this method
Character.valueOf()
should generally be used in preference to the constructorCharacter(char)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values.
Use int
instead. Use -1
to represent "no char".
Lots of precedence of this pattern, for example int read() in java.io.Reader
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With