Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why aren't Java references not null by default?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading