-1

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?

1 Answers1

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