-1

How the empty string ("") store in memory in Java?

The empty string "" is 0 length, then how to store it in memory?

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Guo
  • 1,761
  • 2
  • 22
  • 45
  • 8
    0 length doesn't mean 0 memory footprint. – Ryan Leach Jul 04 '17 at 01:25
  • There's a memory for a reference, and memory in the heap the reference points to. – cs95 Jul 04 '17 at 01:25
  • 2
    The same way any other string is stored, i.e. a `String` object with a `char[]` field. There is nothing special about the empty string, it just has a `char[]` of length 0. – Andreas Jul 04 '17 at 01:48
  • To add to Andreas' comment: when an array such as a `char[]` is stored, the length has to be stored somewhere (otherwise how would the program know what the length is?). – ajb Jul 04 '17 at 02:37

1 Answers1

1

Borrowed from this answer. The program prints 32 bytes for the empty string (and 0 for "" which is in the string pool).

public static void main(String... args) {
    long free1 = free();
    String s = "";
    long free2 = free();
    String s2 = new String("");
    long free3 = free();
    if (free3 == free1) System.err.println("You need to use -XX:-UseTLAB");
    System.out.println("\"\" took " + (free1 - free2) + " bytes and new String(\"\") took " + (free2
            - free3) + " bytes.");
}

private static long free() {
    return Runtime.getRuntime().freeMemory();
}

Also, check this answer.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161