ANN Java-1e Draft 2 Ch.2 p.1/49 2 Some Java Fundamentals In language, clarity is everything. CONFUCIUS Kindly enter them in your notebook. And, in order to refer to them conveniently, let's call them A, B, and Z. THE TORTOISE IN LEWIS CARROLL' S What the Tortoise Said to Achilles For, contrary to the unreasoned opinion of the ignorant, the choice of a system of numeration is a mere matter of convention. BLAISE PASCAL CHAPTER CONTENTS 2.1 Example: A Payroll Program 2.2 Types, Variables, and Constants PART OF THE PICTURE: Data Representation 2.3 Other Basic Program Features 2.4 Java Documentation 2.5 Introduction to GUI Engineering The preceding chapter focused on the software development process and it included three simple Java programs. However, because we had not yet undertaken a systematic study of the Java programming language, our walk-throughs of these programs were simplified considerably. We glossed over many language details in the hope that you would gain some understanding — albeit incomplete — of what was going on in these programs. In this chapter we will present some of these fundamental features of Java more precisely and in more detail.
49
Embed
2 Some Java Fundamentals - Calvin Collegenyhl/Java1e/Java-Ch2.pdf · ANN Java-1e Draft 2 Ch.2 p.1/49 2 Some Java Fundamentals In language, clarity is everything. C ONFUCIUS Kindly
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
ANN Java-1e Draft 2 Ch.2 p.1/49
2 Some Java FundamentalsIn language, clarity is everything.
CONFUCIUS
Kindly enter them in your notebook.
And, in order to refer to them conveniently,
let's call them A, B, and Z.
THE TORTOISE IN LEWIS CARROLL' S
What the Tortoise Said to Achilles
For, contrary to the unreasoned opinion of the ignorant, the choice of a system of
numeration is a mere matter of convention.
BLAISE PASCAL
CHAPTER CONTENTS
2.1 Example: A Payroll Program
2.2 Types, Variables, and Constants
PART OF THE PICTURE: Data Representation
2.3 Other Basic Program Features
2.4 Java Documentation
2.5 Introduction to GUI Engineering
The preceding chapter focused on the software development process and it included three simple
Java programs. However, because we had not yet undertaken a systematic study of the Java
programming language, our walk-throughs of these programs were simplified considerably. We
glossed over many language details in the hope that you would gain some understanding — albeit
incomplete — of what was going on in these programs. In this chapter we will present some of
these fundamental features of Java more precisely and in more detail.
ANN Java-1e Draft 2 Ch.2 p.2/49
2.1 Example: A Payroll ProgramIn the opening section of the preceding chapter we looked at a simple program that displayed a
welcome greeting. In the last section we developed a program to calculate speed from a given
distance and time. In this section we will consider a simple payroll program and use it to illustrate
some of the features of the Java language studied in the next two sections.
ProblemChuck Controller is the sole employee in Cawker City Candy Company's accounting department
and is finding it increasingly difficult to keep up with his duties. As a first step in computerizing
some of the department's tasks, he would like a program to calculate employee wages. Currently,
each employee is paid a fixed hourly rate for any number of hours — no overtime is paid.
Object-Centered Design In developing this program, we will use the OCD (object-centered design) method described in the
previous chapter:
1. Describe the program's behavior
2. Identify the problem's objects
3. Identify the problem's operations
4. Organize these objects and operations in an algorithm
Behavior. Our program should display on the screen a prompt for the number of hours worked
and the hourly rate. The user will enter these real values at the keyboard. The program should
read these numbers and compute the wages. It should display wages along with a descriptive
label.
The Problem's Objects. From our behavioral description of what the program is to do, we can
identify the following objects in this problem:
ANN Java-1e Draft 2 Ch.2 p.3/49
Description ofProblem's Object Type Kind Name
the program ?? ?? ??
screen Screen variable theScreen
prompt for hours and rate String constant none
number of hours worked double variable hoursWorked
hourly pay rate double variable hourlyRate
keyboard Keyboard variable theKeyboard
wages double variable wages
descriptive label String constant none
Operations. Again, using our behavioral description, we can identify the operations needed to
solve this problem:
i. Display strings (the prompts) on the screen
ii. Read nonnegative real number (hours and hourlyRate) from the keyboard
iii. Compute wages
iv. Display a real value (wages) and a string on the screen
As we saw in Section 1.3, the input and output operations (i, ii, and iv) are provided by the
ann.easyio package. The wages are calculated by
wages = hoursWorked × hourlyRate
which requires the following operations:
iii-a. Multiplication of reals
iii-b. Store a real value in a variable
Algorithm. Organizing these objects and operations into an algorithm gives:
1. Construct Screen object theScreen and the Keyboard object theKeyboard.
2. Ask object theScreen to display a prompt for the hours worked by the employee.
3. Ask object theKeyboard to read a real value and store it in hoursWorked.
4. Ask object theScreen to display a prompt for the employee's hourly pay rate.
5. Ask object theKeyboard to read a real value and store it in hourlyRate.
6. Compute wages = hoursWorked × hourlyRate.
7. Ask objecttheScreen to display wages and a descriptive label.
ANN Java-1e Draft 2 Ch.2 p.4/49
Coding, Execution, and TestingFigure 2.1 shows one way to implement the preceding algorithm as a program. Also shown are
two sample runs with test data for which the output can be easily verified and a third execution
with some more realistic data values.
Figure 2.1 Payroll program
/* Payroll.java computes an employee's wages. * Input: Hours worked by the employee and his/her hourly rate * Output: Employee's wages (no overtime pay) */
import ann.easyio.*; // Keyboard, Screen
class Payroll extends Object{ public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard();
theScreen.print("\nEnter the number of hours worked by employee: "); double hoursWorked = theKeyboard.readDouble(); theScreen.print("\nEnter the employee's hourly pay rate: "); double hourlyRate = theKeyboard.readDouble();
Enter the number of hours worked by employee: 3Enter the employee's hourly pay rate: 1.25
Employee's wages: $3.75
Enter the number of hours worked by employee: 39Enter the employee's hourly pay rate: 8.75
Employee's wages: $341.25
MaintenanceOne obvious enhancement to the program would be to design it to process both regular and
overtime wages. But this requires a selection structure, which we describe and study in Chapters 4
and 6. Another improvement would be to design the program to process any number of employees
ANN Java-1e Draft 2 Ch.2 p.5/49
without have to re-execute it each time. But this requires using a repetition structure, which will be
studied in Chapters 4 and 7.
Another way the program could be improved is not revealed by the sample runs. However, if
we execute it with 39 hours worked and a pay rate of $8.11, the output produced is
Enter the number of hours worked by employee: 39Enter the employee's hourly pay rate: 8.11
Employee's wages: $316.28999999999996
Obviously, the format of the value for wages is not good. It would be better to display wages as
$316.29, with two decimal places. Similarly, for 39 hours worked and a pay rate of $8.10, the
output produced is
Enter the number of hours worked by employee: 39Enter the employee's hourly pay rate: 8.10
Employee's wages: $315.9
This isn't as bad as the preceding sample run, but it would be preferable to display the wages with
two decimal places — $315.90.
For this kind of formatting problem, we have included a printFormatted() method in the
ann.easyio package. In can be used in several different forms, which are described in the For
Reference section at the end of this chapter. Figure 2.2 shows a modified version of the program in
Figure 2.1 that uses one of these forms to display the value of wages with two decimal digits.
Figure 2.2 Payroll program — revised.
/* Payroll2.java computes an employee's wages. * Input: Hours worked by the employee and his/her hourly rate * Output: Employee's wages (no overtime pay) */
import ann.easyio.*; // Keyboard, Screen
class Payroll2{ public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard();
theScreen.print("Enter the number of hours worked by employee: "); double hoursWorked = theKeyboard.readDouble(); theScreen.print("Enter the employee's hourly pay rate: ");
ANN Java-1e Draft 2 Ch.2 p.6/49
double hourlyRate = theKeyboard.readDouble();
double wages = hoursWorked * hourlyRate; theScreen.print("\nEmployee's wages: $"); theScreen.printFormatted(wages, 2) theScreen.println(); // or as a chain of messages: // theScreen.print("\nEmployee's wages: $") // .printFormatted(wages, 2).println(); }}
Sample runs:
Enter the number of hours worked by employee: 39Enter the employee's hourly pay rate: 8.11
Employee's wages: $316.29
Enter the number of hours worked by employee: 39Enter the employee's hourly pay rate: 8.10
Employee's wages: $315.90
As the comment indicates, the printFormattted() method can be chained together with
println() and print() methods. (See the Java Info section at the end of Chapter 1 for an
explanation of how this works.) The call to println() with no argument at the end of the chained
messages simply causes subsequent output to appear on a new line.
In the next two sections we examine in detail several basic Java features. We will use the
preceding program along with those in the preceding chapter to illustrate these features.
2.2 Types, Variables, and ConstantsAs we discussed in Chapter 1, object-centered design involves identifying the real-world objects in a
problem, identifying what operations on those data objects are needed, and then developing and
encoding an algorithm that manipulates these objects and operations in the problem. To allow the
Java compiler to check that the corresponding software objects within a program are being used
properly, Java requires that the types of these objects be specified, or declared, before they are
used. In this section, we take a first look at the types that Java provides, the values in these types,
and some of the basic syntax rules for choosing names for and declaring variables, constants, and
ANN Java-1e Draft 2 Ch.2 p.7/49
objects to store these values. The Part of the Picture section that follows shows how values of
various types are stored in memory and the next chapter describes these types in more detail.
TypesBefore the name of a variable, constant, or method can be used in a program, its name must be
associated with a type, which informs the Java compiler how much space in memory must be
allocated for each kind of value. The program in Figure 2.2 uses several types:
• void, the type associated with the main() method
• String [], the type associated with an argument (args) that can be passed to the main
method (and, in general, the type associated with arrays of strings)
• Keyboard, the type associated with theKeyboard
• Screen, the type associated with theScreen
• double, the type associated with real values such as hoursWorked, hourlyRate, and wages
Java divides types into two categories:
1. Primitive types
2. Reference types
The primitive types include int, double, and char and can be thought of as the basic building
blocks in Java. Table 2.1 gives a listing of Java's primitive types and shows their memory
requirements.
Table 2.1 Java's Primitive Types
Type Kind of Values Number of Bits
byte
short
int
long
float
double
void
boolean
char
very small integers
small integers
integers
large integers
small reals
reals
none
logical (true/false) values
individual characters
8
16
32
64
32
64
0
1
16
ANN Java-1e Draft 2 Ch.2 p.8/49
Reference types, such as String, Screen, and Keyboard, on the other hand, are built out
of other types. In Java, programmers use classes to create new types, so a different way of
saying this is that reference types are classes, while primitive types are not. A particular instance
of a class is called an object. For example, String values are objects, Keyboard values are
objects, and Screen values are objects; but int values and double values are not objects. The type
of an object must be a reference type.
Notice that the names of primitive types begin with a lowercase letter — e.g., void, int, and
double, The names of reference types (e.g., String, Keyboard, and Screen) usually begin with
an uppercase letter.
Another difference between the two kinds of types is that primitive -type names are Java
keywords but reference-type names are not. That is, the names of primitive type have predefined
meanings in the Java language, which are thus known to the Java compiler, while the meanings of
reference-type names must be explained to the compiler. Classes must be declared either within the
file that uses them (as in the case of our Payroll class) or declared in a package (e.g.,
ann.easyio) so that a program in a different file can import them with an import statement (e.g.,
import ann.easyio.*;). Primitive and reference types are discussed in more detail in Chapter 3.
Literals. A value of a given type is known as a literal.1 Table 2.2 gives some examples of
literals for a few of Java’s standard types:
Table 2.2 Some Primitive Type Literals
Type Example Literals
int
double
String
char
boolean
-3, -1, 0, 1, 100, 1000
-2.5, 0.0, 0.001, 3.0e8, 1.0E-4
"Hi", "Bye", "Enter your name: "
'A', 'B', 'a', 'b', '0', '1', '$', '+', '\n'
true, false
1 This usage of the word literal in computing refers to any value typed in by the programmer that does not change
during program execution — the string of characters you type is (literally) the value you get.
ANN Java-1e Draft 2 Ch.2 p.9/49
NOTE
From this list, it should be evident that integers and whole numbers are int (or byte, or short, or
long) literals; real numbers are double (or float) literals; sequences of characters enclosed in
double-quotes are String literals; individual characters enclosed in single-quotes are char literals;
and the keywords true and false are boolean literals.
IdentifiersIn the program in Figure 2.1, we chose the name theKeyboard to refer to a Keyboard object, the
name theScreen to refer to a Screen object, and the names hoursWorked, hourlyRate, and
wages for variables that could store double values. Such names are called identifiers. They
may not be keywords such as import, double, public, class, and extends, because these
words already have predefined meanings in Java. A complete list of the Java keywords is given in
Appendix B.
In Java, an identifier may begin with a letter or _ (underscore), which may be followed by any
number of these characters or digits.2 This allows a programmer to use meaningful names that
describes what that they represent. For example, the identifier
hoursWorked
is more meaningful than the shortened identifier
h
which might refer to height, hard-drive, henrys, hertz, or hackers, or anything else beginning with
the letter ‘h’. One should resist the temptation to use a short identifier simply to save a few
keystrokes. Complete words are preferable to abbreviations. It is good programming practice to
use meaningful identifiers that suggest what they represent, because such names make a program
easier to read and understand. They serve, therefore, as part of the program's documentation and
thus facilitate program maintenance.
2 A letter is any of the symbols A - Z, a - z, or a Unicode character that is a letter in another language. Also, a
dollar sign ($) is allowed, but it is used for special purposes.
ANN Java-1e Draft 2 Ch.2 p.10/49
NOTE
It is important to remember that Java is case sensitive — that is, it distinguishes between
uppercase and lowercase. For example, hourlyRate and hourlyrate are different identifiers in
Java. Similarly, the main method must be named main, not Main. One must be very careful to use
the same names consistently.
Although different programmers have different programming styles, there are certain naming
conventions that are commonly practiced. The following guidelines are used by many Java
programmers and are the ones we will follow in this text:
Classes: Names are given in lowercase, except for the first letter of each word in the name.
For example: Payroll, Screen, Keyboard, StringBuffer, and JOptionPane.
Variables: Names of storage locations for values that can change are given names like class
names, except that the first letter of the name is in lowercase. For example:
wages, hourlyRate, and theKeyboard.
Constants: Names of storage locations for values that do not change are in uppercase. If a
name consists of several words, these words are separated by underscore (_)
characters. For example: PI, METERS_PER_KILOMETER, and SECONDS_PER_HOUR
(see Figure 1.3).
Methods: Method names are like variable names, but are followed by parentheses. For
example: main(), readDouble(), print(), and println(),
These naming conventions make it easy to determine what role a name plays in a program: whether
it is the name of a class, a variable, a constant, or a method.
Declaration StatementsAny name in a program that is not a Java keyword is an identifier, and while keywords have
predefined meanings to the Java compiler, identifiers do not. To use an identifier in a program, we
must provide the compiler with the meaning of that identifier before its first use. This is
accomplished by using a declaration statement. For example, in the program in Figure 2.1,
the lines
Watch
Out!
ANN Java-1e Draft 2 Ch.2 p.11/49
class Payroll extends Object{
...}
declare the identifier Payroll as the name of a class. Similarly, the lines
public static void main(String [] args){ ...}
declare the identifier main as the name of a method within the Payroll class. The package
ann.easyio contains the declarations of Keyboard and Screen, so the statement
import ann.easyio.*;
has the effect of declaring to the compiler that identifiers Keyboard and Screen are names of
classes.
Variable Declarations. Most programs store data values in memory locations from which these
values can be retrieved and processed. Locations whose contents may change because new values
are stored in them are called variables and are declared for the Java compiler with variable
declaration statements. For example, the declaration statement
double hoursWorked = theKeyboard.readDouble();
in the main method in Figure 2.1 declares that hoursWorked is of type double and is to be
initialized with the value returned by the readDouble() method from the Keyboard class. If the
value 38.5 is entered by the user, we might picture the result of this declaration as follows:
38.5hoursWorked
If we replaced the declaration with
double hoursWorked;
the memory location associated with hourWorked would contain an undefined value, which we
might picture as
?hoursWorked
The statement
ANN Java-1e Draft 2 Ch.2 p.12/49
hoursWorked = theKeyboard.readDouble();
could then be used to give hoursWorked a value.
Whereas the memory allocated to a primitive-type variable stores a value of that type, the
memory for a reference-type variable stores the address of the memory location where its value is
stored.3 To illustrate, consider the first statement in the main method in Figure 2.1:
Screen theScreen = new Screen();
The first part of this declaration,
Screen theScreen
declares the name theScreen as a variable and allocates memory to theScreen that can be used to
store a memory address:
theScreen
The new operator finds a location in memory where this Screen object will be stored and stores its
address in the memory location allocated to theScreen. We might picture this as follows:
theScreen
a objectScreen
We will study reference types in more detail in Chapters 3 and 6.
The general form of a variable declaration is:
Variable Declaration
Form:
type variable_name;
or
type variable_name = expression;
where:
3 It may help to remember that in computing, the word reference is commonly used as a synonym for address.
ANN Java-1e Draft 2 Ch.2 p.13/49
type may be any type that is known to the compiler;
variable_name is a valid identifier; and
expression is any expression (as described in later sections) producing a value whose
type is type.
Purpose:
Instructs the compiler to reserve sufficient memory to store a value of type type, and
associates that memory with the name variable_name. In the second form,
variable_name is initialized to the value of expression.
For additional documentation, some programmers also add brief comments after each variable
declaration to indicate what the variable represents, how it is to be used, its valid values, and so
on. The following examples illustrate this style:
int idNumber; // Student Id-Number
double cumulativeHours, // Total credits to date hoursThisTerm, // Credits this semester gradePointAverage; // Cumulative GPA: 0.0 - 4.0
Displays doubleValue with numIntDigits to the left of the decimal point,
rounded to numDecDigits digits to the right of the decimal point, and with
empty positions filled with fillChar
Like the print() and println(), printFormatted returns the Screen object to which the
message is sent, so that these three methods can be used in a chain of messages.
n JOptionPane' s showInputDialog() Forms
Method Description
showInputDialog(Object prompt) Construct an input dialog in the center of thescreen with title "Input", and in it displayprompt, a text field for user input, and buttonslabeledOk and Cancel. The prompt can be aString, graphic image, or other Java Object.Clicking Ok returns the contents of the text fieldas a String; clicking Cancel returns the specialvalue null.
showInputDialog(Component parent,
Object prompt)
Construct an input dialog as above, withposition relative to parent, which may be awindow, frame, panel, or other Java GUIComponent. If parent is null, the dialog iscentered on the screen as above.
Construct an input dialog as above, but withspecified title, and whose message isdescribed by messageKind, which determinesthe appearance of the dialog (see Table 2.3).
Construct an input dialog as above, but withspecified icon, whose valid values are given byselectionValues, and whose default selectionis initialSelection.
Construct a message dialog positioned relative toparent with title "Message" and displayingmessage. The parent may be a window,frame, panel, or other Java GUI Component. Ifparent is null, the dialog is centered on thescreen. The message may be any Java Object.