Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does s take 3 bytes in Java? when : String s = "abc"; Java

If I write this in Java:

String s = "abc";  

Does s only occupy 3 bytes in the memory?
If true, how JVM finds the end of the String object?
Does this take more bytes in memory?

like image 244
Al2O3 Avatar asked Sep 16 '12 14:09

Al2O3


1 Answers

It takes more than 3 bytes, read on for full explanation from this page

For reasons we'll explore below, the minimum memory usage of a Java String (in the Hotspot Java 6 VM) is generally as follows:

Minimum String memory usage (bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)

Or, put another way:

  • multiply the number of characters of the String by two;
  • add 38;
  • if the result is not a multiple of 8, round up to the next multiple of 8;
  • the result is generally the minimum number of bytes taken up on the heap by the String.

This page from the same website also details ways in which you can save memory using classes different than String

like image 52
Dreen Avatar answered Oct 06 '22 00:10

Dreen