In Java, is null an existing object on the heap?
I'm trying to understand the difference between an uninitialized local variable (what does not compile) and one initialized with null (what compiles).
In Java, is null an existing object on the heap?
I'm trying to understand the difference between an uninitialized local variable (what does not compile) and one initialized with null (what compiles).
See here:
The Java IAQ:
Infrequently Answered Questions
http://norvig.com/java-iaq.html
Do a search on the page for "Is null an object". It's about halfway down the page.
Or, to save you the clicking, the answer is no, it is not an object. Being null means that no object is referenced.
This question highlights the connection between scope and definite assignment. If you step through the code below in a debugger, you can see several features as you break on each line:
i
is not in scope.i
is in scope, but "not a known variable in the current context."i
has been assigned, and it has the value null
.i
has the value 1, which will be incremented after line 4.Listing:
Integer i;
i = null;
i = Integer.valueOf(1);
i++;
Addendum:
So, what's the difference between null and uninitialized?
Prior to definite assignment, a local variable's value is inaccessible; any attempt to access the value is rejected at compile-time. Once a definite value is assigned, even null
, that value can be accessed. This is a critical security feature in Java. In some languages, an uninitialized variable may reference values in memory left by a previous process.
Addendum: The content of a frame's local variables prior to initialization is unspecified. The bytecode verifier precludes bytecode that accesses uninitialized memory, but deviant bytecode is possible.
a local variable that hasn't been assigned yet, probably points to null too. I'm not a JVM expert, but that seems to be the logical choice.
so compiler checks for you to make sure you assigned something to the variable. other than that there's no difference. at runtime local variables not initialized yet are assigned to null.
Null is NOT an object. In fact it is the opposite of an object, and why you can't make method calls against a reference pointing at null. If you really must know what null is you can think of it as a something like zero. In fact a reference that points to null doesn't take up anymore memory, ie. zero. It has no value so it's a reference that doesn't refer to any object.
In Java you have to initialize a variable before you can use it. For reasons of history Java doesn't want you to assume values so the compiler forces you to assign a value to it. Part of the reasons for this is the bugs and security problems that C caused because it didn't initialize values or force you to do it before they were used. Java does initialize some values for primitives, and instance variables: 0, 0.0, false, and null etc, but for local variables you have to give it a value. It's for your own protection. :-)