img
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is
false
b is
true
This
is executed.
10 >
9 is true
There are three interesting things to notice about this program. First, as you can see, when
a boolean value is output by println( ), "true" or "false" is displayed. Second, the value of a
boolean variable is sufficient, by itself, to control the if statement. There is no need to write
an if statement like this:
if(b == true) ...
Third, the outcome of a relational operator, such as <, is a boolean value. This is why the
expression 10 > 9 displays the value "true." Further, the extra set of parentheses around 10 > 9
is necessary because the + operator has a higher precedence than the >.
A Closer Look at Literals
Literals were mentioned briefly in Chapter 2. Now that the built-in types have been formally
described, let's take a closer look at them.
Integer Literals
Integers are probably the most commonly used type in the typical program. Any whole
number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values,
meaning they are describing a base 10 number. There are two other bases which can be used
in integer literals, octal (base eight) and hexadecimal (base 16). Octal values are denoted in Java
by a leading zero. Normal decimal numbers cannot have a leading zero. Thus, the seemingly
valid value 09 will produce an error from the compiler, since 9 is outside of octal's 0 to 7 range.
A more common base for numbers used by programmers is hexadecimal, which matches
cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You signify a hexadecimal
constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A
through F (or a through f ) are substituted for 10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer value. Since Java is
strongly typed, you might be wondering how it is possible to assign an integer literal to one
of Java's other integer types, such as byte or long, without causing a type mismatch error.
Fortunately, such situations are easily handled. When a literal value is assigned to a byte or
short variable, no error is generated if the literal value is within the range of the target type.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home