Reputation: 673
To further explain my question. Does simply writing String foo;
allocate memory. Or is memory only set aside when the variable is given value for the first time? Thanks.
Upvotes: 1
Views: 1179
Reputation: 310840
You have not declared an object here. You have declared a reference variable. The variable occupies memory, and so does the object it refers to after you initialize it.
Upvotes: 1
Reputation: 11020
I'm going to answer this differently because I think the linked (duplicate) answers are wrong.
Memory IS allocated when you just declare a reference.
public MyClass {
public String s;
}
That reference s
needs 8 byes on the heap (typically, most JVMs). The memory has to be there.
Now when you assign it, more memory gets allocated.
public static void main( String args... ) {
MyClass c = new MyClass();
c.s = new String("Hello Memory");
}
The string "Hello Memory"
takes memory too, but the reference s
still takes up 8 byes on the heap and is part of the memory that gets allocated when MyClass
gets created. In addition, all Java objects have about 8 bytes of additional overhead on the heap (all Java objects have a monitor associated with them, so that takes overhead).
And in the method main
, c
takes 8 bytes as well (on the stack), in addition to the memory that that new
needs to allocate on the heap. I really think you need to account for this sort of allocation if you want to understand how memory works.
I'm probably going to flub this up, because memory allocation gets tricky, but here's how this program allocates memory, starting with main
.
First c
gets allocated when main
is invoked: 8 bytes.
Then new MyClass()
allocates 16 bytes (the size of s
+ 8 bytes overhead) on the heap.
Next, (are you ready for this?) new String("Hello Memory");
allocates 48 bytes on the heap. Why? Java strings are declared like this:
public final String {
private final char[] string;
private int hashcode;
}
So 8 bytes overhead for the string object, plus 12 bytes overhead for the array (arrays are objects and also need the length of the array, so normal 8 byte overhead + 4 bytes for the length). The hashcode
field takes another 4 bytes, and the string data "Hello Memory" takes 24 bytes (12 chars
at 2 bytes each). If I've done that right it adds up to 48 bytes. C programmers are either laughing or crying.
Upvotes: 2
Reputation: 2234
The memory isn't allocated until you create the string. Simply defining the string is not enough. If you create a string object using string literal, that object is stored in the string constant pool and whenever you create a string object using new keyword, such object is stored in the heap memory.
For example, when you create string objects like below, they will be stored in the String Constant Pool.
String s = "abc";
And when you create string objects using new keyword like below, they will be stored in the heap memory.
String s5 = new String("abc");
Upvotes: 0