In most programs, objects are created and objects are destroyed, depending on the data and on what is being computed. A reference variable sometimes does and sometimes does not refer to an object. You may need a way to erase the reference inside a variable without creating a new reference. You do this by assigning null to the variable.
The value null is a special value that means "no object." A reference variable is set to null when it is not referring to any object.
String a = // 1. an object is created;
new String("stringy"); // variable a refers to it
String b = null; // 2. variable b refers to no
// object.
String c = // 3. an object is created
new String(""); // (containing no characters)
// variable c refers to it
if (a != null) // 4. statement true, so
System.out.println(a); // the println(a) executes.
if (b != null) // 5. statement false, so the
System.out.println(b); // println(b) is skipped.
if (c != null) // 6. statement true, so the
System.out.println(c); // println(c) executes (but
// it has no characters to
// print).
Run Output:
stringy
Variables a and c are initialized to object references. Variable b is initialized to null. Note that variable c is initialized to a reference to a String object containing no characters. Therefore, println(c) executes, but it has no characters to print. Having no characters is different from the value being null.
Last modified: December 12, 2022
Back to Object References