System, but they may not be reproduced for publication



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

type var­name;
Here, type specifies the type of variable being declared, and var­name is the name of
the variable. In addition to int, Java supports several other data types.
The following line of code assigns myVar1 the value 1024:
In Java, the assignment operator is the single equal sign. It copies the value on its right
side into the variable on its left.
The next line of code outputs the value of myVar1 preceded by the string "myVar1
contains ":
In this statement, the plus sign causes the value of myVar1 to be displayed after the
string that precedes it. This approach can be generalized. Using the + operator, you can
chain together as many items as you want within a single println( ) statement.
The next line of code assigns myVar2 the value of myVar1 divided by 2:
This line divides the value in myVar1 by 2 and then stores that result in myVar2.
Thus, after the line executes, myVar2 will contain the value 512. The value of myVar1
will be unchanged. Like most other computer languages, Java supports a full range of
arithmetic operators, including those shown here:


Here are the next two lines in the program:
Two new things are occurring here. First, the built­in method print( ) is used to
display the string "myVar2 contains myVar1 / 2: ". This string is not followed by a new
line. This means that when the next output is generated, it will start on the same line.
The print( ) method is just like println( ), except that it does not output a new line
after each call. Second, in the call to println( ), notice that myVar2 is used by itself.
Both print( ) and println( ) can be used to output values of any of Java’s built­in
types.
One more point about declaring variables before we move on: It is possible to declare
two or more variables using the same declaration statement. Just separate their names
by commas. For example, myVar1 and myVar2 could have been declared like this:
ANOTHER DATA TYPE
In the preceding program, a variable of type int was used. However, a variable of type
int can hold only whole numbers. Thus, it cannot be used when a fractional component
is required. For example, an int variable can hold the value 18, but not the value 18.3.
Fortunately, int is only one of several data types defined by Java. To allow numbers
with fractional components, Java defines two floating­point types: float and double,
which represent single­ and double­precision values, respectively. Of the two, double
is the most commonly used.
To declare a variable of type double, use a statement similar to that shown here:
Here, x is the name of the variable, which is of type double. Because x has a floating­
point type, it can hold values such as 122.23, 0.034, or –19.0.


To better understand the difference between int and double, try the following
program:
The output from this program is shown here:
Ask the Expert
Q
: Why does Java have different data types for integers and floating­
point values? That is, why aren’t all numeric values just the same type?
A
: Java supplies different data types so that you can write efficient programs. For
example, integer arithmetic is faster than floating­point calculations. Thus, if you
don’t need fractional values, then you don’t need to incur the overhead associated
with types float or double. Second, the amount of memory required for one type


of data might be less than that required for another. By supplying different types,
Java enables you to make best use of system resources. Finally, some algorithms
require (or at least benefit from) the use of a specific type of data. In general, Java
supplies a number of built­in types to give you the greatest flexibility.
As you can see, when v is divided by 4, a whole­number division is performed, and the
outcome is 2—the fractional component is lost. However, when the double variable x
is divided by 4, the fractional component is preserved, and the proper answer is
displayed.
There is one other new thing to notice in the program. To print a blank line, simply call
println( ) without any arguments.
Try This 1­1
Converting Gallons to Liters
Although the preceding sample programs illustrate several important features of the
Java language, they are not very useful. Even though you do not know much about Java
at this point, you can still put what you have learned to work to create a practical
program. In this project, we will create a program that converts gallons to liters. The
program will work by declaring two double variables. One will hold the number of the
gallons, and the second will hold the number of liters after the conversion. There are
3.7854 liters in a gallon. Thus, to convert gallons to liters, the gallon value is multiplied
by 3.7854. The program displays both the number of gallons and the equivalent
number of liters.
1. Create a new file called GalToLit.java.
2. Enter the following program into the file:


3. Compile the program using the following command line:
4. Run the program using this command:
You will see this output:
5. As it stands, this program converts 10 gallons to liters. However, by changing the
value assigned to gallons, you can have the program convert a different number of
gallons into its equivalent number of liters.
TWO CONTROL STATEMENTS
Inside a method, execution proceeds from one statement to the next, top to bottom.
However, it is possible to alter this flow through the use of the various program control
statements supported by Java. Although we will look closely at control statements later,
two are briefly introduced here because we will be using them to write sample
programs.
The if Statement


The if Statement
You can selectively execute part of a program through the use of Java’s conditional
statement: the if. The Java if statement works much like the IF statement in any other
language. It determines the flow of program execution based on whether some
condition is true or false. Its simplest form is shown here:
if(condition) statement;
Here, condition is a Boolean expression. (A Boolean expression is one that evaluates to
either true or false.) If condition is true, then the statement is executed. If condition is
false, then the statement is bypassed. Here is an example:
In this case, since 10 is less than 11, the conditional expression is true, and println( )
will execute. However, consider the following:
In this case, 10 is not less than 9. Thus, the call to println( ) will not take place.
Java defines a full complement of relational operators that may be used in a conditional
expression. They are shown here:
Notice that the test for equality is the double equal sign.
Here is a program that illustrates the if statement:


The output generated by this program is shown here:


Notice one other thing in this program. The line
declares three variables, a, b, and c, by use of a comma­separated list. As mentioned
earlier, when you need two or more variables of the same type, they can be declared in
one statement. Just separate the variable names by commas.
The for Loop
You can repeatedly execute a sequence of code by creating a loop. Loops are used
whenever you need to perform a repetitive task because they are much simpler and
easier than trying to write the same statement sequence over and over again. Java
supplies a powerful assortment of loop constructs. The one we will look at here is the
for loop. The simplest form of the for loop is shown here:
for(initialization; condition; iteration) statement;
In its most common form, the initialization portion of the loop sets a loop control
variable to an initial value. The condition is a Boolean expression that tests the loop
control variable. If the outcome of that test is true, statement executes and the for loop
continues to iterate. If it is false, the loop terminates. The iteration expression
determines how the loop control variable is changed each time the loop iterates. Here is
a short program that illustrates the for loop:
The output generated by the program is shown here:


In this example, count is the loop control variable. It is set to zero in the initialization
portion of the for. At the start of each iteration (including the first one), the conditional
test count < 5 is performed. If the outcome of this test is true, the println( )
statement is executed, and then the iteration portion of the loop is executed, which
increases count by 1. This process continues until the conditional test is false, at which
point execution picks up at the bottom of the loop. As a point of interest, in
professionally written Java programs, you will almost never see the iteration portion of
the loop written as shown in the preceding program. That is, you will seldom see
statements like this:
The reason is that Java includes a special increment operator that performs this
operation more efficiently. The increment operator is ++ (that is, two plus signs back to
back). The increment operator increases its operand by one. By use of the increment
operator, the preceding statement can be written like this:
Thus, the for in the preceding program will usually be written like this:
You might want to try this. As you will see, the loop still runs exactly the same as it did
before.
Java also provides a decrement operator, which is specified as – –. This operator
decreases its operand by one.
CREATE BLOCKS OF CODE
Another key element of Java is the code block. A code block is a grouping of two or
more statements. This is done by enclosing the statements between opening and closing
curly braces. Once a block of code has been created, it becomes a logical unit that can be


used any place that a single statement can. For example, a block can be a target for
Java’s if and for statements. Consider this if statement:
Here, if w is less than h, both statements inside the block will be executed. Thus, the
two statements inside the block form a logical unit, and one statement cannot execute
without the other also executing. The key point here is that whenever you need to
logically link two or more statements, you do so by creating a block. Code blocks allow
many algorithms to be implemented with greater clarity and efficiency.
Here is a program that uses a block of code to prevent a division by zero:
The output generated by this program is shown here:
Ask the Expert
Q
: Does the use of a code block introduce any run­time inefficiencies?
In other words, does Java actually execute the { and }?


A
: No. Code blocks do not add any overhead whatsoever. In fact, because of their
ability to simplify the coding of certain algorithms, their use generally increases
speed and efficiency. Also, the { and } exist only in your program’s source code.
Java does not, per se, execute the { or }.
In this case, the target of the if statement is a block of code and not just a single
statement. If the condition controlling the if is true (as it is in this case), the three
statements inside the block will be executed. Try setting i to zero and observe the result.
You will see that the entire block is skipped.
As you will see later in this book, blocks of code have additional properties and uses.
However, the main reason for their existence is to create logically inseparable units of
code.
SEMICOLONS AND POSITIONING
In Java, the semicolon is a separator. It is often used to terminate a statement. In
essence, the semicolon indicates the end of one logical entity.
As you know, a block is a set of logically connected statements that are surrounded by
opening and closing braces. A block is not terminated with a semicolon. Instead, the
end of the block is indicated by the closing brace.
Java does not recognize the end of the line as a terminator. For this reason, it does not
matter where on a line you put a statement. For example,
is the same as the following, to Java:
Furthermore, the individual elements of a statement can also be put on separate lines.
For example, the following is perfectly acceptable:


Breaking long lines in this fashion is often used to make programs more readable. It
can also help prevent excessively long lines from wrapping.
INDENTATION PRACTICES
You may have noticed in the previous examples that certain statements were indented.
Java is a free­form language, meaning that it does not matter where you place
statements relative to each other on a line. However, over the years, a common and
accepted indentation style has developed that allows for very readable programs. This
book follows that style, and it is recommended that you do so as well. Using this style,
you indent one level after each opening brace, and move back out one level after each
closing brace. Certain statements encourage some additional indenting; these will be
covered later.
Try This 1­2
Improving the Gallons­to­Liters Converter
You can use the for loop, the if statement, and code blocks to create an improved
version of the gallons­to­liters converter that you developed in the first project. This
new version will print a table of conversions, beginning with 1 gallon and ending at 100
gallons. After every 10 gallons, a blank line will be output. This is accomplished
through the use of a variable called counter that counts the number of lines that have
been output. Pay special attention to its use.
1. Create a new file called GalToLitTable.java.
2. Enter the following program into the file:


3. Compile the program using the following command line:
4. Run the program using this command:
Here is a portion of the output that you will see:


THE JAVA KEYWORDS
Sixty­one keywords are currently defined in the Java language (see 
Table 1­1
). These
keywords, combined with the syntax of the operators and separators, form the
definition of the Java language. In general, keywords cannot be used as names for a
variable, class, or method. The exceptions to this rule are the context­sensitive
keywords added by JDK 9 to support modules. (See 
Chapter 15
for details.) Also,
beginning with JDK 9, an underscore by itself is considered a keyword in order to
prevent its use as the name of something in your program.


Table 1­1 The Java Keywords
The keywords const and goto are reserved but not used. In the early days of Java,
several other keywords were reserved for possible future use. However, the current
specification for Java defines only the keywords shown in 
Table 1­1
.
In addition to the keywords, Java reserves four other names. Three have been part of
Java since the start: true, false, and null. These are values defined by Java. You may
not use these words for the names of variables, classes, and so on. Beginning with JDK
10, the word var has been added as a context­sensitive, reserved type name. (See
Chapter 5
for details on var.)
IDENTIFIERS IN JAVA
In Java an identifier is, essentially, a name given to a method, a variable, or any other
user­defined item. Identifiers can be from one to several characters long. Variable
names may start with any letter of the alphabet, an underscore, or a dollar sign. Next
may be either a letter, a digit, a dollar sign, or an underscore. The underscore can be
used to enhance the readability of a variable name, as in line_count. Uppercase and
lowercase are different; that is, to Java, myvar and MyVar are separate names. Here
are some examples of acceptable identifiers:
Remember, you can’t start an identifier with a digit. Thus, 12x is invalid, for example.


In general, you cannot use the Java keywords as identifier names. Also, you should not
use the name of any standard method, such as println, as an identifier. Beyond these
two restrictions, good programming practice dictates that you use identifier names that
reflect the meaning or usage of the items being named.
THE JAVA CLASS LIBRARIES
The sample programs shown in this chapter make use of two of Java’s built­in methods:
println( ) and print( ). These methods are accessed through System.out. System is
a class predefined by Java that is automatically included in your programs. In the larger
view, the Java environment relies on several built­in class libraries that contain many
built­in methods that provide support for such things as I/O, string handling,
networking, and graphics. The standard classes also provide support for a graphical
user interface (GUI). Thus, Java as a totality is a combination of the Java language
itself, plus its standard classes. As you will see, the class libraries provide much of the
functionality that comes with Java. Indeed, part of becoming a Java programmer is
learning to use the standard Java classes. Throughout this book, various elements of
the standard library classes and methods are described. However, the Java library is
something that you will also want to explore more on your own.

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   7   8   9   10   11   12   13   14   ...   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ə