String Object size
I want to know the actual contents of a String Object, along with the String that is stored.
I created String Literals with increasing count of characters, and checked the size of the object created. Please tell me why the objects given below take the size (in bytes) they are taking. If they store one character in 2 bytes, then what are the other bytes are used to store ?
String s1 = "a";//0 bytes
String s2 = "bb"; // 20 bytes
String s3 = "ccc";// 24 bytes
String s4 = "dddd"; // 24 bytes
String s5 = "eeeee";// 24 bytes
String s6 = "ffffff";// 24 bytes
String s7 = "ggggggg"; // 28 bytes
String s8 = "hhhhhhhh";// 28 bytes
String s9 = "iiiiiiiii"; // 28 bytes
String s10 = "jjjjjjjjjj";// 28 bytes
String s11 = "kkkkkkkkkkk";// 32 bytes
String s12 = "llllllllllll";// 32 bytes
[866 byte] By [
kakarotha] at [2007-11-26 16:47:37]

> Nope, its fine. Its running fine and memory usage is
> monitored using DevPartner Java Profiler.
> Infact the line String s1 = "a"; is marked and the
> objects created and bytes created after this line is
> given, which happen to be 0, 0.
The tool isn't correct.
Right. I think I might know what your problem is.
1) It is NOT fine. If you think an instance of a string can ever be 0 bytes then, well, I don't know what to suggest other than ask yourself "how can comething that's there exist in zero space?"
2) When compiled you may find that certain code is ignored as I'm guessing your reference to s1 is never used hence the optimizer will ignore/omit it.
3) The memory reserved by the JVM increases but does not shrink which might have something to do with your results. Are the figures you give an estimate for the size of each object or the current used memory?
Ted.
I wondered the same thing, and according to the experiment on this page, [url]http://martin.nobilitas.com/java/sizeof.html[/url] Strings take up 2 x String.length + 38 bytes, give or take 2 bytes ( the test isn't entirely exact ). This makes sense though, considering that Java strings are stored in Unicode which uses 16 bits to store a character ( two 8-bit bytes ) and I assume the other 38+/-2 bytes are to store the object methods, the length of the string, and other data. He does the experiment much like you do, except he uses a feature of Java and large amounts of objects to test the system's memory.
Simple logic should tell you that you can't store anything in 0 bytes, that would be like a book that is 0 pages long. So, obviously your experiment has gone a bit pear shaped.