Java Reference
In-Depth Information
Table 4.4
Differences between
char
and
String
char
String
Type of value
primitive
object
Memory usage
2 bytes
depends on length
Methods
none
length
,
toUpperCase
,
. . .
Number of letters
exactly 1
0 to many
Surrounded by
apostrophes:
'c'
quotes:
"Str"
Comparing
<
,
>=
,
==
, . . .
equals
It is also legal to create a
char
value that represents an escape sequence:
char newline = '\n';
In the previous chapter we discussed
String
objects. The distinction between
char
and
String
is a subtle one that confuses many new Java programmers. The
main difference is that a
String
is an object, but a
char
is a primitive value. A
char
occupies a very small amount of memory, but it has no methods. Table 4.4 summa-
rizes several of the differences between the types.
Why does Java have two types for such similar data? The
char
type exists primar-
ily for historical reasons; it dates back to older languages such as C that influenced
the design of Java.
So why would a person ever use the
char
type when
String
is available? It's
often necessary to use
char
because some methods in Java's API use it as a parame-
ter or return type. But there are also a few cases in which using
char
can be more
useful or simpler than using
String
.
The characters of a
String
are stored inside the object as values of type
char
.
You can access the individual characters through the object's
charAt
method, which
accepts an integer index as a parameter and returns the character at that index. We
often loop over a string to examine or change its characters. For example, the follow-
ing method prints each character of a string on its own line:
public static void printVertical(String message) {
for (int i = 0; i < message.length(); i++) {
char ch = message.charAt(i);
System.out.println(ch);
}
}
Values of type
char
are stored internally as 16-bit integers. A standard encoding
scheme called Unicode determines which integer value represents each character.
(Unicode will be covered in more detail later in this chapter.) Since characters are
Search WWH ::
Custom Search