When we only declare an object of a class without instantiating it like below, does it treats as null or empty or else?
Example1: Directory objDEntry;
Example2: Directory objDEntry = null;
Is there a difference between Example1 and Example2 or they are same?
It depends; if you declare a field, e.g.
public class MyClass {
// objDEntr will be initialized by null
Directory objDEntr;
// the initialization is redundant here
Directory objDEntry2 = null;
...
there's no difference, since fields are initialized by their default values and null is the default value for reference types. However, local variables are not initialized by default; so
public static void MyMethod() {
// objDEntry contains trash, must be initialized further
Directory objDEntry;
// objDEntry2 is null
Directory objDEntry2 = null;
...
in the "Example 1" objDEntry contains trash, while in the "Example 2" objDEntry is properly initialized and contains null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With