0

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.

aborted
  • 4,481
  • 14
  • 69
  • 132

2 Answers2

1

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.

Community
  • 1
  • 1
taylorcressy
  • 966
  • 8
  • 23
0

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.

Community
  • 1
  • 1
UnTraDe
  • 3,747
  • 10
  • 36
  • 60
  • 1
    Can you quote some source to prove your last line. How is `null` usually that address? In Java you don't get to deal with addresses directly. – Rohit Jain Feb 27 '14 at 10:22
  • You are correct, I was mistakenly thinking that since i'm used to C++ and there NULL is an acutal definition for 0. – UnTraDe Feb 27 '14 at 11:10