What is the difference between NULL in C++ and null in Java?
- by Stephano
I've been trying to figure out why C++ is making me crazy typing NULL. Suddenly it hits me the other day; I've been typing null (lower case) in Java for years. Now suddenly I'm programming in C++ and that little chunk of muscle memory is making me crazy.
Wikiperipatetic defines C++ NULL as part of the stddef:
A macro that expands to a null pointer
constant. It may be defined as
((void*)0), 0 or 0L depending on the
compiler and the language.
Sun's docs tells me this about Java's "null literal":
The null type has one value, the null
reference, represented by the literal
null, which is formed from ASCII
characters. A null literal is always
of the null type.
So this is all very nice. I know what a null pointer reference is, and thank you for the compiler notes. Now I'm a little fuzzy on the idea of a literal in Java so I read on...
A literal is the source code
representation of a fixed value;
literals are represented directly in
your code without requiring
computation.
There's also a special null literal
that can be used as a value for any
reference type. null may be assigned
to any variable, except variables of
primitive types. There's little you
can do with a null value beyond
testing for its presence. Therefore,
null is often used in programs as a
marker to indicate that some object is
unavailable.
Ok, so I think I get it now. In C++ NULL is a macro that, when compiled, defines the null pointer constant. In Java, null is a fixed value that any non-primitive can be assigned too; great for testing in a handy if statement.
Java does not have pointers, so I can see why they kept null a simple value rather than anything fancy. But why did java decide to change the all caps NULL to null?
Furthermore, am I missing anything here?