I've seen this question for other languages (C and C++). But I still don't get why it is like this in Java as well. Where could it be useful that a reference is declared but not set to null?
Asked
Active
Viewed 54 times
-1
-
If they were not null, what object would they reference? FWIW, C doesn't have references, and C++ references can't be created without assigning them to something. – Dawood ibn Kareem Nov 23 '21 at 19:31
-
Are you saying that in Java, the default for a reference is *not* null? Or are you saying you can't imagine why a reference should *ever* be initialized to something other than null? – Scott Hunter Nov 23 '21 at 19:31
-
I've edited the question. – Hazar Ulaş Nov 23 '21 at 19:32
-
1I think he means "why are they by default not initialized to null?". – user16632363 Nov 23 '21 at 19:33
1 Answers
1
Thing ref;
if (someCondition)
ref = oneThing;
else
ref = anotherThing;
There is no benefit in initializing 'ref' to null in the above code, at least not as long as neither assignment can throw an exception.
It's not "useful" that it is uninitialized, it's merely that there's no point in initializing it.
I wish it were not like that - I'd prefer initialization of local variables to work like member variables - but that is how it is.
I assume it's for efficiency reasons. If you don't have to initialize local variables, allocation is pretty much just an adjustment of the stack pointer.

user16632363
- 1,050
- 3
- 6
-
I see. Still, it feels like I should always check for exceptions after assigning the reference. Hence, I must set it to null manually. – Hazar Ulaş Nov 23 '21 at 19:45