Search code examples
javastringnullheap-memory

String with value null and memory allocation


If a String Object references to a null value, is there any memory allocated for this value?

e.g. String str = ""; String str = null;

str's value is null, or empty String, is this allocated somewhere?

TEXT ADDED what happens when a String reference points to null (how do you specify this null and still not allocating memory for this "specification"?), how is this information stored? because the reference is practically storing an address.


Solution

  • Case -1 :

    String s = null;
    

    here, memory is allocated only for the reference s. null is not an object. So no memory is allocared for that.

    Case -2 :

    String s = ""; // empty string 
    

    Here, memory is allocated to both String reference s as well as the actual String value "" (Yes, "" is different from null)