Java - Variable Memory Size

Java Conceptuel Diagram


memory size of a variable.

To get the memory size of a variable, you can do it:

  • statically with the data type declaration
  • dynamically with the Java runtime. See calculation


Primitive types


A single alphanumeric character is 1 byte in length


A string is simply a sequence of characters (of 1 byte each) with an additional null character appended to the tail of the characters to denote the end of the string; therefore, a String has a variable length that is equal to the number of characters in the string, plus one (for the null character). For example, the string hello is composed of 5 characters (h, e, l, l, and o), plus the null character (written as \0), and is therefore 6 bytes long. Note that Java does not use this style to store strings, but we will use this scheme for demonstration purposes. For more on Java strings in memory, see this post.


  • A char value[] (A char is 2 bytes) from the String implementation code source
  • An int hash. (An int is 4 bytes) from the String implementation code source
  • Object Overhead:
    • An array stores its dimensions, for example.
    • And array (an object) and the string will incur extra memory from the garbage collector storing information about them.

The answer should be: <MATH> yourstring.length * 2 + 4 + ObjectOverhead </MATH> but there is no reliable way to calculate this, because each JRE and JDK has no obligation to the size of object overhead.


A number as being 2 bytes long.


Reference: a reference to another object must be large enough to hold the address of the other object in memory (so that we can find the referenced object); for the purposes of this article, we will assume an address in memory can be stored in 2 bytes, and therefore, a reference will be 2 bytes in length.


long m0 = Runtime.getRuntime().freeMemory();
String s = new String("WhatEvver");
long m1 = Runtime.getRuntime().freeMemory();
System.out.println(m0 - m1);

Documentation / Reference

Share this page:
Follow us:
Task Runner