How is an empty string stored internally in the memory? I was thinking about an empty string memory representation and can't quite comprehend it. Is there some specific ASCII value for it? What is an empty string exactly?
A String object is a Java Object like any other. It is an object that has a length attribute, which ultimately is stored in a Java object as an int. An empty String has length 0, and thus that int == 0. In actual implementations, a String object internally has a reference to a char[] object (an array of chars).
For an empty String, that reference might be null. In theory the String implementation might always have a non null array reference, and use the length of the array of chars as the String length int, in which case you question would be equivalent to asking about the memory representation of an empty array.
See the OpenJDK implementation for example:
private final char value[];
is the reference to the array of characters
private final int count;
is the length of the String, as you can see for the default constructor, which creates an empty String:
public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}
(You might be wondering why that implementation has an offset. This is so a sub-string can share the same character array as its parent string, which reduces memory use in many cases).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With