How does memory space allocation affects the operations on string like length in (both) C and in Java ? (This is in reference to the fact that C string variable packs 4 bytes per word where as a java string variable packs two half words per word)
The fact is that there ain't any C string variable in C , they are just arrays ;arrays of characters. One char in C occupies 1 byte. The string literals are just stored as a array of characters and a terminating \0 is appended at the end.
In the Java programming language, strings are objects. A String contains the following:
This means even if the string contains no characters, it will require 4 bytes for the char array reference, plus 3*4=12 bytes for the three int fields, plus 8 bytes of object header. This gives 24 bytes (which is a multiple of 8 so no "padding" bytes are needed so far). Then, the (empty) char array will require a further 12 bytes (arrays have an extra 4 bytes to store their length), plus in this case 4 bytes of padding to bring the memory used by the char array object up to a multiple of 16. So in total, an empty string uses 40 bytes.
Calculating the memory usage by the string you will have to take into account the fact that a character in array is 2 bytes.
JAVA->String.length() is a constant time operation in the number of characters contained in the string because java string class stores the length as a field.
C-> strlen() traverse the whole array until the \0 to calculate the length of the string its runtime grows with the size of the string.
A C string is a nul byte terminated sequence of bytes.
A Java String is an Object which has a length known and references an array of 16-bit chars
The memory allocation for a String is much higher, but it supports UTF-16 characters and an O(1) length operation. i.e. it can be faster in some cases.
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