Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation of character in c and java

Tags:

java

c

string

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)

like image 575
notsogeek Avatar asked May 01 '26 17:05

notsogeek


2 Answers

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:

  1. a char array— thus a separate object— containing the actual characters;
  2. an integer offset into the array at which the string starts; the length of the string;
  3. another int for the cached calculation of the hash code.

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.

like image 58
0decimal0 Avatar answered May 04 '26 05:05

0decimal0


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.

like image 45
Peter Lawrey Avatar answered May 04 '26 05:05

Peter Lawrey