Reputation: 4541
This kind of confuses me and I'm pretty unsure how this exactly works in Java.
Lets say we have these two variables:
String a = "Hello World";
String b;
It's pretty obvious that a
takes a little space in the stack and points to the value "Hello World" in the heap. But what's the case with b
?
Does it only create that reference in the stack and point nowhere in the heap? I'm assuming its value is currently null
.
Upvotes: 0
Views: 674
Reputation: 965
Well strictly speaking, if you have a non-trivial unused local variable, the compiler will most likely be optimized to never even put the reference on the stack. Otherwise, in the obscure case, it might point to null. However, this is the Java way of doing things. This issue of what happens on the heap is a design choice and discussed in detail here.
In the C-world, during the pre-processing phase, the preprocessor populates a "table" with information such as "type", "reference", "value", and some other data. This is how we establish the difference between declaration and initialization. So, if we never point the object to any "value", it never gets initialized... thus, the heap gets left alone. Note that pointing something to null is still initializing it.
Upvotes: 1
Reputation: 3867
Yes you are correct, both will acutal create a local pointer in the stack which will point to an address in the heap. In case of a it will point to some address allocated in the heap, in case of b it points to null which in Java, is a special type which specifies invalid pointer. You can read more about the null itself here: What is null in Java?
Also, Primitives types like int, long, etc... usually have a default value and they are not reference themselves, Since String is an object, you actually create a reference in the stack and set it to somewhere on the heap or to null.
Upvotes: 0