Java Reference
In-Depth Information
5.2.5 Testing for Null
An object reference can have the special value
null
if it refers to no object at all.
It is common to use the
null
value to indicate that a value has never been set. For
example,
The
null
reference refers to no object.
String middleInitial = null; //
Not set
if (. . .)
middleInitial = middleName.substring(0, 1);
You use the
==
operator (and not
equals
) to test whether an object reference is a
null
reference:
if (middleInitial == null)
System.out.println(firstName + " " + lastName);
else
System.out.println(firstName + " " +
middleInitial + "." + lastName);
Note that the
null
reference is not the same as the empty string Ȓȓ. The empty
string is a valid string of length 0, whereas a
null
indicates that a string variable
refers to no string at all.
S
ELF
C
HECK
3.
What is the value of
s.length()
if
s
is
a.
the empty string Ȓȓ?
b.
the string Ȓ ȓ containing a space?
c.
null
?
4.
Which of the following comparisons are syntactically incorrect?
Which of them are syntactically correct, but logically questionable?
String a = "1";
String b = "one";
double x = 1;