THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

symbolic constants defined in the Float and Double classessee Chapter 8.


A double constant cannot be assigned directly to a float variable, even if the value of the double is
within the valid float range. The only constants you may directly assign to float variables and fields are
float constants.


7.2.6. String Literals


String literals appear with double quotes: "along". Any character can be included in string literals, with the
exception of newline and " (double quote). Newlines are not allowed in the middle of strings. If you want to
embed a newline character in the string, use the escape sequence \n. To embed a double quote use the escape
sequence \". A string literal references an object of type String. To learn more about strings, see Chapter
13.


Characters in strings can be specified with the octal digit syntax, but all three octal digits should be used to
prevent accidents when an octal value is specified next to a valid octal digit in the string. For example, the
string "\0116" is equivalent to "\t6", whereas the string "\116" is equivalent to "N".


7.2.7. Class Literals


Every type (primitive or reference) has an associated instance of class Class that represents that type. These
instances are often referred to as the class object for a given type. You can name the class object for a type
directly by following the type name with ".class", as in


String.class
java.lang.String.class
java.util.Iterator.class
boolean.class


The first two of these class literals refer to the same instance of class Class because String and
java.lang.String are two different names for the same type. The third class literal is a reference to the
Class instance for the Iterator interface mentioned on page 129. The last is the Class instance that
represents the primitive type boolean.


Since class Class is generic, the actual type of the class literal for a reference type T is Class, while
for primitive types it is Class where W is the wrapper class for that primitive type. But note, for
example, that boolean.class and Boolean.class are two different objects of type
Class. Generic types are discussed in Chapter 11, and the class Class is discussed in Chapter
16.


Exercise 7.2: Write a class that declares a field for each of the primitive numeric types, and try to assign
values using the different literal formsfor example, try to assign 3.5f to an int field. Which literals can be
used with which type of field? Try changing the magnitude of the values used to see if that affects things.


7.3. Variables


A variable is a storage location[6] something that can hold a valueto which a value can be assigned. Variables
include fields, local variables in a block of code, and parameters. A variable declaration states the identifier
(name), type, and other attributes of a variable. The type part of a declaration specifies which kinds of values

Free download pdf