Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

byte and char

Status
Not open for further replies.

satellite03

IS-IT--Management
Dec 26, 2003
248
IN
how many bytes "abc" is ?

does it contain 3*2=6 bytes ? (as each char = 2 bytes, there are 3 chars ,'a','b','c' inside "abc")

how can i check it ?
 
If you say "abc" is a String object, which is in effect a char[], then yes, "abc", in as much as it is 3 chars, is 6 bytes.

Now whether it actually takes up more space or not I'm not sure. In C/C++, you also require a NULL terminator to end the string, and I'm guessing you probably need the same behind all the fluffiness of Java - so in reality it could be 7 bytes (if the NULL terminator is 1 byte) ...

--------------------------------------------------
Free Database Connection Pooling Software
 
You could do
Code:
"abd".getBytes().length;

It wouldn't include any hidden NULL terminator or 'fluff' [smile], but it would tell you the number of bytes used by the characters (using the default charset).

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
It all depends what he wants to know for, I suppose. But your reminder that String is an object and therefore takes up MUCH more room byte-wise than the characters it represents is a good one, Dian.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
Hmmmmm .... how come that this :

String s = "abc";
System.out.println(s.getBytes().length);

prints out "3" then ?

Is Java just counting the number of chars in the (in effect) char array, and not the object bytes, or is a String just a plain wrapper for a char array ?

I'm just not sure !


--------------------------------------------------
Free Database Connection Pooling Software
 
That returns the number of data structures of the primitve Java type byte stored in that array, not the actual size in bytes.

The String object needs more memory to store, for example, the length of the char array, that is not computed on each access but is a member of the String class.

An answer to this is contained on the source code for String class.

Just in case, one more article on sizes:
Cheers,

Dian
 
Thanks for that Dian ... guess I've been in C char* land too long lately :)

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top