Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable that can contain most memory space?

Tags:

java

c

What type of variable that can contain 1,000,000,000(a decimal number) takes the most memory space?

  1. int in C
  2. string in C
  3. string in Java(which uses unicode)
like image 323
kamalbhai Avatar asked Mar 15 '26 14:03

kamalbhai


1 Answers

A Java String. Under the hood A Java String consists of an object with 3 fields, one of which points to a separate array object containing the characters. Plus of course, Java Strings are composed of 16 bit characters1.

If you are worried about memory usage over all other criteria, don't use Java. But for most applications, memory usage is the least of your concerns.

It is worth noting that 1,000,000,000 can be represented using a Java int which will be the same size as a C signed or unsigned (32 bit) integer.

Furthermore, a C int is not necessarily big enough to represent 1,000,000,000. On some platforms, int is 16 bits, and this is allowed by the C standard.


1 - Actually, this is Java platform dependent. For example, in Java 9 they modified the String implementation to use one byte per character for strings that are composed entirely of characters in the range 0 to 255. See this article. But despite this, a Java string still takes more space than a C string.

like image 191
Stephen C Avatar answered Mar 18 '26 02:03

Stephen C