Java Reference
In-Depth Information
sense for Java to have a number of special syntax features designed to make han‐
dling strings easy. Let's look at some examples of special syntax features for strings
that Java provides.
String literals
As we saw in
Chapter 2
, Java allows a sequence of characters to be placed in double
quotes to create a literal string object. Like this:
String
pet
=
"Cat"
;
Without this special syntax, we would have to write acres of horrible code like this:
char
[]
pullingTeeth
=
{
'C'
,
'a'
,
't'
};
String
pet
=
new
String
(
pullingTeeth
);
This would get tedious extremely quickly, so it's no surprise that Java, like all
modern programming languages, provides a simple string literal syntax. The string
literals are perfectly sound objects, so code like this is completely legal:
System
.
out
.
println
(
"Dog"
.
length
());
toString()
This method is defined on
Object
, and is designed to allow easy conversion of any
object to a string. This makes it easy to print out any object, by using the method
System.out.println()
. This method is actually
PrintStream::println
because
System.out
is a static field of type
PrintStream
. Let's see how this method is
defined:
public
void
println
(
Object
x
)
{
String
s
=
String
.
valueOf
(
x
);
synchronized
(
this
)
{
print
(
s
);
newLine
();
}
}
This creates a new string by using the static method
String::valueOf()
:
public
static
String
valueOf
(
Object
obj
)
{
return
(
obj
==
null
)
?
"null"
:
obj
.
toString
();
}
The static
valueOf()
method is used instead of
toString()
directly, to avoid a
NullPointerException
in the case where
obj
is
null
.