The String class is used for text manipulation. As you read, you will learn different ways to create Strings, methods to manipulate Strings, the String concatenation operator '+', and about how Strings are immutable.
6. The Empty String
Answer:
The code ""
calls for a literal, which is a
String
object. Although the object exists, it
contains no characters (since there are no
characters inside ""
).
The reference variable c
is initialized to a
reference to this String
object. This is most
certainly a different value than null.
The Empty String
class NullDemo1{ public static void main (String[] arg) { String a = "Random Jottings"; // 1. an object is created; // variable a refers to it String b = null; // 2. variable b refers to no object. String c = ""; // 3. an object is created // (containing no characters); // variable c refers to it if ( a != null ) // 4. ( a != null ) is true, so System.out.println( a ); // 5. println( a ) executes. if ( b != null ) // 6. ( b != null ) is false, so System.out.println( b ); // 7. println( b ) is skipped. if ( c != null ) // 8. ( c != null ) is true, so System.out.println( c ); // 9. println( c ) executes. // (but it has no characters to print.) } } |
A String
object that contains no characters is still an object. Such an object is called an empty string. It is similar to having a blank sheet of paper (different from having no paper at all). Overlooking this difference
is one of the classic confusions of computer programming. It will happen to you. It happens to me. To prepare for future confusion, study the program, step-by-step.
The System.out.println()
method expects a reference to a String
object as a parameter
. The example program tests that each variable contains a String
reference
before calling println()
with it. (If println()
gets a null
parameter, it prints out "null" which would be OK. But some methods crash if they get a null parameter. Usually you
should ensure that methods get the data they expect.)
Question 6:
Examine the following code snippet:
String alpha = new String("Red Rose") ; alpha = null; . . .
- Where is an object constructed?
- What becomes of that object?