Initialize vs not initialize

Question is in

String text1;
String text2 = null;

Is there any difference? Why is it possible at all to ‘initialize’ with null?

I specify my question.
Why someone will write String text2 = null;?


Contact contact1;
List<Contact> contacts = [...];
if (!contacts.isEmpty()) {
 contact1 = contacts[0];
} else {
 contact1 = new Contact();

and in another class I see

Contact contact2 = null;
List<Contact> contacts = [...];
if (!contacts.isEmpty()) {
 contact2 = contacts[0];
} else {
 contact2 = new Contact();

If it were different persons – ok – this might be the habit.


They really are on in the same as when you initialize a variable with no value, it’s set to null automatically.

You can test this by running this in an execute anonymous window

String s1;
system.debug('s1 value is: ' + s1);

String s2 = null;
system.debug('s2 value is: ' + s2);

This code produces the following

enter image description here

As far as why someone would explicitly set it to null, I really think that might just be habit or preference, as I can’t think of a specific reason as to why you would NEED to.

Similar to how some people initialize a list by using list<sObject> vs sObject[]. Neither one is incorrect and they both equate to the same thing.

I may be wrong and perhaps someone can prove me wrong, but I can’t think of a reason to HAVE to set it explicitly to null.

Source : Link , Question Author : Andrii Muzychuk , Answer Author : Chris Duncombe

Leave a Comment