Java Reference
In-Depth Information
Note Declaring a float literal requires appending f to the end of the literal. Otherwise, the compiler tries to
make it into a double value and then complains that it can't cast from double to float. Similarly, you can put d at
the end of a double literal's declaration. However, that is redundant because double is the default floating-point
Literals pop up all over the place, often without anyone stopping to think about it (after all, we're
usually trying to get the computer to do something). Every time we write a loop that starts at 0 and
counts to some value, we use a literal (in that case, an integer literal). A number of other literals are
common in nearly all programming languages and tasks. In set theory (which informs a lot of
programming and especially database programming), the only three values that matter are 0, 1, and
many. Consequently, 0 and 1 appear over and over again throughout all kinds of software. The empty
string ( "" —sometimes handy for comparing String objects) and the single space ( " " —handy for linking
String objects without inventing a new and large word in the process) also appear often.
Escaping Characters
Variables of type char can have several special values. First, singe quotation marks ('), double quotation
marks ( " ), and backslashes (\) all have to be marked as special (that's called escaping a character), so
that the JVM knows you want one of those characters. Otherwise, it would process all your single
quotations as the beginning or end of a char and all your double quotations as the beginning or end of a
String object. The backslash character has to be escaped because it is the escape character. If it couldn't
itself be escaped, then every backslash would indicate an escaped character, which would be a real
problem. Escaped characters (often called escape sequences because they consist of at least two
characters—the escape character and at least one other character) are also used for non-graphical
characters (often called control characters). There's even a character called Bell. It never appears, but it
can (if your computer enables it) make your computer beep. The Bell (or Alert) character's escape
sequence is \a . All of that might not make sense, so let's consider some examples in Listing 3-3 to make
things clearer.
Listing 3-3. Examples of escaping characters
// Let's start with double quotation marks
// The following line throws an error because meow isn't defined
System.out.println("My cat says, "meow."");
// so the line has to be
System.out.println("My cat says, \"meow.\"");
// which will produce this output: My cat says, "meow."
// And now single quotation marks
// The following line throws an error because ' never has a matching '
System.out.println("' is my favorite character");
// so the line has to be
System.out.println("\' is my favorite character");
Search WWH ::

Custom Search