System, but they may not be reproduced for publication



Yüklə 83 Mb.
Pdf görüntüsü
səhifə12/82
tarix19.04.2023
ölçüsü83 Mb.
#106251
1   ...   8   9   10   11   12   13   14   15   ...   82
Java A Beginner’s Guide, Eighth Edition ( PDFDrive )

 Chapter 1 Self Test
1.
What is bytecode and why is it important to Java’s use for Internet programming?
2.
What are the three main principles of object­oriented programming?
3.
Where do Java programs begin execution?
4.
What is a variable?
5.
Which of the following variable names is invalid?
A. count
B. $count
C. count27
D. 67count


6.
How do you create a single­line comment? How do you create a multiline comment?
7.
Show the general form of the if statement. Show the general form of the for loop.
8.
How do you create a block of code?
9.
The moon’s gravity is about 17 percent that of earth’s. Write a program that
computes your effective weight on the moon.
10.
Adapt 
Try This 1­2
so that it prints a conversion table of inches to meters. Display
12 feet of conversions, inch by inch. Output a blank line every 12 inches. (One meter
equals approximately 39.37 inches.)
11.
If you make a typing mistake when entering your program, what sort of error will
result?
12.
Does it matter where on a line you put a statement?


Chapter 2
Introducing Data Types and Operators
Key Skills & Concepts

Know Java’s primitive types

Use literals

Initialize variables

Know the scope rules of variables within a method

Use the arithmetic operators
History
Topics
Tutorials
Offers & Deals
Highlights
Settings
Support
Sign Out


A

Use the relational and logical operators

Understand the assignment operators

Use shorthand assignments

Understand type conversion in assignments

Cast incompatible types

Understand type conversion in expressions
t the foundation of any programming language are its data types and operators, and
Java is no exception. These elements define the limits of a language and determine the
kind of tasks to which it can be applied. Fortunately, Java supports a rich assortment of
both data types and operators, making it suitable for any type of programming.
Data types and operators are a large subject. We will begin here with an examination of
Java’s foundational data types and its most commonly used operators. We will also take
a closer look at variables and examine the expression.
WHY DATA TYPES ARE IMPORTANT
Data types are especially important in Java because it is a strongly typed language. This
means that all operations are type­checked by the compiler for type compatibility.
Illegal operations will not be compiled. Thus, strong type checking helps prevent errors
and enhances reliability. To enable strong type checking, all variables, expressions, and
values have a type. There is no concept of a “type­less” variable, for example.
Furthermore, the type of a value determines what operations are allowed on it. An
operation allowed on one type might not be allowed on another.
JAVA’S PRIMITIVE TYPES
Java contains two general categories of built­in data types: object­oriented and non­
object­oriented. Java’s object­oriented types are defined by classes, and a discussion of
classes is deferred until later. However, at the core of Java are eight primitive (also
called elemental or simple) types of data, which are shown in 
Table 2­1
. The term
primitive is used here to indicate that these types are not objects in an object­oriented
sense, but rather, normal binary values. These primitive types are not objects because


of efficiency concerns. All of Java’s other data types are constructed from these
primitive types.
Table 2­1 Java’s Built­in Primitive Data Types
Java strictly specifies a range and behavior for each primitive type, which all
implementations of the Java Virtual Machine must support. Because of Java’s
portability requirement, Java is uncompromising on this account. For example, an int
is the same in all execution environments. This allows programs to be fully portable.
There is no need to rewrite code to fit a specific platform. Although strictly specifying
the range of the primitive types may cause a small loss of performance in some
environments, it is necessary in order to achieve portability.
Integers
Java defines four integer types: byte, short, int, and long, which are shown here:
As the table shows, all of the integer types are signed positive and negative values. Java
does not support unsigned (positive­only) integers. Many other computer languages
support both signed and unsigned integers. However, Java’s designers felt that
unsigned integers were unnecessary.
NOTE


Technically, the Java run­time system can use any size it wants to store a primitive
type. However, in all cases, types must act as specified.
The most commonly used integer type is int. Variables of type int are often employed
to control loops, to index arrays, and to perform general­purpose integer math.
When you need an integer that has a range greater than int, use long. For example,
here is a program that computes the number of cubic inches contained in a cube that is
one mile by one mile, by one mile:
Here is the output from the program:
Clearly, the result could not have been held in an int variable.
The smallest integer type is byte. Variables of type byte are especially useful when
working with raw binary data that may not be directly compatible with Java’s other
built­in types. The short type creates a short integer. Variables of type short are
appropriate when you don’t need the larger range offered by int.
Ask the Expert


Q
: You say that there are four integer types: int, short, long, and byte.
However, I have heard that char can also be categorized as an integer
type in Java. Can you explain?
A
: The formal specification for Java defines a type category called integral types,
which includes byte, short, int, long, and char. They are called integral types
because they all hold whole­number, binary values. However, the purpose of the
first four is to represent numeric integer quantities. The purpose of char is to
represent characters. Therefore, the principal uses of char and the principal uses
of the other integral types are fundamentally different. Because of the differences,
the char type is treated separately in this book.
Floating-Point Types
As explained in 
Chapter 1
, the floating­point types can represent numbers that have
fractional components. There are two kinds of floating­point types, float and double,
which represent single­ and double­precision numbers, respectively. Type float is 32
bits wide and type double is 64 bits wide.
Of the two, double is the most commonly used, and many of the math functions in
Java’s class library use double values. For example, the sqrt( ) method (which is
defined by the standard Math class) returns a double value that is the square root of
its double argument. Here, sqrt( ) is used to compute the length of the hypotenuse,
given the lengths of the two opposing sides:


The output from the program is shown here:
One other point about the preceding example: As mentioned, sqrt( ) is a member of
the standard Math class. Notice how sqrt( ) is called; it is preceded by the name
Math. This is similar to the way System.out precedes println( ). Although not all
standard methods are called by specifying their class name first, several are.
Characters
In Java, characters are not 8­bit quantities like they are in many other computer
languages. Instead, Java uses Unicode. Unicode defines a character set that can
represent all of the characters found in all human languages. In Java, char is an
unsigned 16­bit type having a range of 0 to 65,535. The standard 8­bit ASCII character
set is a subset of Unicode and ranges from 0 to 127. Thus, the ASCII characters are still
valid Java characters.
A character variable can be assigned a value by enclosing the character in single quotes.
For example, this assigns the variable ch the letter X:


You can output a char value using a println( ) statement. For example, this line
outputs the value in ch:
Since char is an unsigned 16­bit type, it is possible to perform various arithmetic
manipulations on a char variable. For example, consider the following program:
The output generated by this program is shown here:
In the program, ch is first given the value X. Next, ch is incremented. This results in ch
containing Y, the next character in the ASCII (and Unicode) sequence. Next, ch is
assigned the value 90, which is the ASCII (and Unicode) value that corresponds to the
letter Z. Since the ASCII character set occupies the first 127 values in the Unicode
character set, all the “old tricks” that you may have used with characters in other
languages will work in Java, too.
Ask the Expert
Q
: Why does Java use Unicode?
A
: Java was designed for worldwide use. Thus, it needs to use a character set that
can represent all the world’s languages. Unicode is the standard character set
designed expressly for this purpose. Of course, the use of Unicode is inefficient for


languages such as English, German, Spanish, or French, whose characters can be
contained within 8 bits. But such is the price that must be paid for global
portability.
THE BOOLEAN TYPE
The boolean type represents true/false values. Java defines the values true and false
using the reserved words true and false. Thus, a variable or expression of type
boolean will be one of these two values.
Here is a program that demonstrates the boolean type:
The output generated by this program is shown here:
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:
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 >.
Try This 2­1
How Far Away Is the Lightning?
In this project, you will create a program that computes how far away, in feet, a listener
is from a lightning strike. Sound travels approximately 1,100 feet per second through
air. Thus, knowing the interval between the time you see a lightning bolt and the time
the sound reaches you enables you to compute the distance to the lightning. For this
project, assume that the time interval is 7.2 seconds.
1. Create a new file called Sound.java.
2. To compute the distance, you will need to use floating­point values. Why? Because
the time interval, 7.2, has a fractional component. Although it would be permissible to
use a value of type float, we will use double in the example.
3. To compute the distance, you will multiply 7.2 by 1,100. You will then assign this
value to a variable.
4. Finally, you will display the result.
Here is the entire Sound.java program listing:


5. Compile and run the program. The following result is displayed:
6. Extra challenge: You can compute the distance to a large object, such as a rock wall,
by timing the echo. For example, if you clap your hands and time how long it takes for
you to hear the echo, then you know the total round­trip time. Dividing this value by
two yields the time it takes the sound to go one way. You can then use this value to
compute the distance to the object. Modify the preceding program so that it computes
the distance, assuming that the time interval is that of an echo.
LITERALS
In Java, literals refer to fixed values that are represented in their human­readable form.
For example, the number 100 is a literal. Literals are also commonly called constants.
For the most part, literals, and their usage, are so intuitive that they have been used in
one form or another by all the preceding sample programs. Now the time has come to
explain them formally.
Java literals can be of any of the primitive data types. The way each literal is
represented depends upon its type. As explained earlier, character constants are
enclosed in single quotes. For example, 'a' and ' %' are both character constants.


Integer literals are specified as numbers without fractional components. For example,
10 and –100 are integer literals. Floating­point literals require the use of the decimal
point followed by the number’s fractional component. For example, 11.123 is a floating­
point literal. Java also allows you to use scientific notation for floating­point numbers.
By default, integer literals are of type int. If you want to specify a long literal, append
an l or an L. For example, 12 is an int, but 12L is a long.
By default, floating­point literals are of type double. To specify a float literal, append
an F or f to the constant. For example, 10.19F is of type float.
Although integer literals create an int value by default, they can still be assigned to
variables of type char, byte, or short as long as the value being assigned can be
represented by the target type. An integer literal can always be assigned to a long
variable.
You can embed one or more underscores into an integer or floating­point literal. Doing
so can make it easier to read values consisting of many digits. When the literal is
compiled, the underscores are simply discarded. Here is an example:
This specifies the value 123,451,234. The use of underscores is particularly useful when
encoding things like part numbers, customer IDs, and status codes that are commonly
thought of as consisting of subgroups of digits.
Hexadecimal, Octal, and Binary Literals
As you may know, in programming it is sometimes easier to use a number system based
on 8 or 16 instead of 10. The number system based on 8 is called octal, and it uses the
digits 0 through 7. In octal the number 10 is the same as 8 in decimal. The base 16
number system is called hexadecimal and uses the digits 0 through 9 plus the letters A
through F, which stand for 10, 11, 12, 13, 14, and 15. For example, the hexadecimal
number 10 is 16 in decimal. Because of the frequency with which these two number
systems are used, Java allows you to specify integer literals in hexadecimal or octal
instead of decimal. A hexadecimal literal must begin with 0x or 0X (a zero followed by
an x or X). An octal literal begins with a zero. Here are some examples:


As a point of interest, Java also allows hexadecimal floating­point literals, but they are
seldom used.
It is possible to specify an integer literal by use of binary. To do so, precede the binary
number with a 0b or 0B. For example, this specifies the value 12 in binary: 0b1100.
Character Escape Sequences
Enclosing character constants in single quotes works for most printing characters, but a
few characters, such as the carriage return, pose a special problem when a text editor is
used. In addition, certain other characters, such as the single and double quotes, have
special meaning in Java, so you cannot use them directly. For these reasons, Java
provides special escape sequences, sometimes referred to as backslash character
constants, shown in 
Table 2­2
. These sequences are used in place of the characters that
they represent.
Table 2­2 Character Escape Sequences
For example, this assigns ch the tab character:
The next example assigns a single quote to ch:
String Literals
Java supports one other type of literal: the string. A string is a set of characters


enclosed by double quotes. For example,
is a string. You have seen examples of strings in many of the println( ) statements in
the preceding sample programs.
In addition to normal characters, a string literal can also contain one or more of the
escape sequences just described. For example, consider the following program. It uses
the \n and \t escape sequences.
The output is shown here:
Ask the Expert
Q
: Is a string consisting of a single character the same as a character
literal? For example, is "k" the same as 'k'?
A
: No. You must not confuse strings with characters. A character literal represents
a single letter of type char. A string containing only one letter is still a string.
Although strings consist of characters, they are not the same type.
Notice how the \n escape sequence is used to generate a new line. You don’t need to use
multiple println( ) statements to get multiline output. Just embed \n within a longer
string at the points where you want the new lines to occur.
A CLOSER LOOK AT VARIABLES


A CLOSER LOOK AT VARIABLES
Variables were introduced in 
Chapter 1
. Here, we will take a closer look at them. As you
learned earlier, variables are declared using this form of statement,

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   8   9   10   11   12   13   14   15   ...   82




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə