Creating Your First
1. For each of the following Java identifiers, note whether it is legal or illegal:
b. last character
2. Name at least three attributes that might be appropriate for each of the following classes:
3. Name at least three objects that are members of each of the following classes:
4. Name at least three classes to which each of these objects might belong:
C h a p t e r o n e
5. Write, compile, and test a class that prints your first name on the screen. Save the class as Name.java.
6. Write, compile, and test a class that prints your full name, street address, city, state, and zip code on three
separate lines on the screen. Save the class as Address.java.
7. Write, compile, and test a class that displays the following pattern on the screen:
Save the class as Tree.java.
8. Write, compile, and test a class that prints your initials on the screen. Compose each initial with five
lines of initials, as in the following example:
J J F
Save the class as Initial.java.
9. Write, compile, and test a class that prints all the objectives listed at the beginning of this chapter. Save the
class as Objectives.java.
10. Write, compile, and test a class that displays the following pattern on the screen:
* * *
Save the class as Diamond.java.
11. Write, compile, and test a class that uses the command window to display the following statement about
“Program comments are nonexecuting statements you add to a file for the purpose of
Also include the same statement in three different comments in the class; each comment should use
one of the three different methods of including comments in a Java class. Save the class as Comments.
12. Modify the Comments.java program in Exercise 11 so that the statement about comments is displayed in
a dialog box. Save the class as CommentsDialog.java.
13. From 1925 through 1963, Burma Shave advertising signs appeared next to highways all across the United
States. There were always four or five signs in a row containing pieces of a rhyme, followed by a final
sign that read “Burma Shave.” For example, one set of signs that has been preserved by the Smithsonian
Institution reads as follows:
You'll soon see 'em
On a shelf
In some museum
Find a classic Burma Shave rhyme on the Web. Write, compile, and test a class that produces a series
of four dialog boxes so that each displays one line of a Burma Shave slogan in turn. Save the class as
14. Write a Java application to display an attractive layout of the information in a typical business card.
Data items in a typical business card include a name, address, city, state, zip code, home phone
number, and work phone number. Save the class as CardLayout.java.
Each of the following files in the Chapter.01 folder on your Student Disk has syntax and/or logic errors.
In each case, determine the problem and fix the errors. After you correct the errors, save each file using
the same filename preceded with Fix. For example, DebugOne1.java will become FixDebugOne1.java.
In 1952, A.S. Douglas wrote his University of Cambridge Ph.D. dissertation on human-computer
interaction, and created the first graphical computer game—a version of Tic-Tac-Toe. The game was
programmed on an EDSAC vacuum-tube mainframe computer. The first computer game is generally
assumed to be “Spacewar!”, developed in 1962 at MIT; the first commercially available video game was
“Pong,” introduced by Atari in 1973. In 1980, Atari’s “Asteroids” and “Lunar Lander” became the first
video games to be registered in the U. S. Copyright Office. Throughout the 1980s, players spent hours
with games that now seem very simple and unglamorous; do you recall playing “Adventure,” “Oregon
Trail,” “Where in the World is Carmen Sandiego?,” or “Myst”?
Today, commercial computer games are much more complex; they require many programmers, graphic
artists, and testers to develop them, and large management and marketing staffs are needed to promote
them. A game might cost many millions of dollars to develop and market, but a successful game might
earn hundreds of millions of dollars. Obviously, with the brief introduction to programming you have
had in this chapter, you cannot create a very sophisticated game. However, you can get started.
For games to hold your interest, they almost always include some random, unpredictable behavior. For
example, a game in which you shoot asteroids loses some of its fun if the asteroids follow the same,
predictable path each time you play the game. Therefore, generating random values is a key component in
creating the most interesting computer games.
Appendix D contains information on generating random numbers. To fully understand the process,
you must learn more about Java classes and methods. However, for now, you can copy the following
statement to generate and use a dialog box that displays a random number between 1 and 10:
JOptionPane.showMessageDialog(null,"The number is " +
(1 + (int)(Math.random() * 10)));
Write a Java application that displays two dialog boxes in sequence. The first asks you to think of a number
between 1 and 10. The second displays a randomly generated number; the user can see whether his
or her guess was accurate. (In future chapters you will improve this game so that the user can enter a
guess and the program can determine whether the user was correct. If you wish, you also can tell the
user how far off the guess was, whether the guess was high or low, and provide a specific number of
repeat attempts.) Save the file as
Achieving success at a job interview involves being able to think on your feet, but you can still be
prepared. The Tough Questions section at the end of each chapter will present questions that an
interviewer might ask at a technical job interview. A particular question might have several good
answers. If you can’t think of an answer right away, try doing some research on the Web or in other Java
1. Describe Java and how it differs from other programming languages.
2. What is the difference between a compiler and an interpreter? Which does Java use? Why?
3. What are the conventions for naming classes and variables in Java? What are the advantages to using these
4. Can you store two public Java classes in the same file? How do you know?
up For DisCussion
Up for Discussion questions are designed to probe your attitudes and opinions about topics that are
relevant to computer programmers and other business professionals.
1. Have you written programs in any programming language before starting this book? If so, what do
you think the advantages and disadvantages of using Java will be? If not, how difficult do you think
writing programs will be compared to other new skills you have mastered?
2. Using the Web, try to discover which computer game is the most popular one ever sold. Have you played
this game? Would you like to? What makes this game so appealing?
3. Obviously, learning Java is useful to a Computer Information Systems major. List several other major
courses of study and discuss how programming skills might be useful to them.
4. Most programming texts encourage students to use many comments in their programs. Many students feel
that writing program comments is a waste of time. What is your opinion? Why? Are there circumstances
under which you would take the opposite stance?
C h a p t e r t w o
using Data Within
1. What is the numeric value of each of the following expressions as evaluated
a. 4 + 6 * 3
g. 16 % 2
b. 6 / 3 * 7
h. 17 % 2
c. 18 / 2 + 14 / 2
i. 28 % 5
d. 16 / 2
j. 28 % 5 * 3 + 1
e. 17 / 2
k. (2 + 3) * 4
f. 28 / 5
l. 20 / (4 + 1)
2. What is the value of each of the following Boolean expressions?
a. 4 > 1
f. 3 + 8 <= 10
b. 5 <= 18
g. 3 != 9
c. 43 >= 43
h. 13 != 13
d. 2 == 3
i. -4 != 4
e. 2 + 5 == 7
j. 2 + 5 * 3 == 21
3. Choose the best data type for each of the following so that no memory storage is wasted. Give an example
of a typical value that would be held by the variable and explain why you chose the type you did.
a. your age
c. your shoe size
b. the U.S. national debt
d. your middle initial
4. a. Write a Java class that declares variables to represent the length and width of a room in feet. Assign
appropriate values to the variables—for example, length = 15 and width = 25. Compute and
display the floor space of the room in square feet (area = length * width). Display explanatory text
with the value—for example, The floor space is 375 square feet. Save the class as Room.
b. Convert the Room class to an interactive application. Instead of assigning values to the length and
width variables, accept them from the user as input. As output, echo the user’s entries as well as
displaying the floor space. Save the revised class as Room2.java.
5. a. Write a Java class that declares variables to represent the length and width of a room in feet and the
price of carpeting per square foot in dollars and cents. Assign appropriate values to the variables.
Compute and display, with explanatory text, the cost of carpeting the room. Save the class as Carpet.
b. Convert the Carpet class to an interactive application. Instead of assigning values to the length, width,
and price variables, accept them from the user as input. Save the revised class as Carpet2.java.
6. a. Write a class that declares a variable named minutes, which holds minutes worked on a job, and
assign a value. Display the value in hours and minutes; for example, 197 minutes becomes 3 hours and
17 minutes. Be sure to use a named constant where appropriate. Save the class as Time.java.
b. Write an interactive version of the Time class that accepts the minutes worked from a user. Save the
class as Time2.java.
7. Write a class that declares variables to hold your three initials. Display the three initials with a period
following each one, as in J.M.F. Save the class as Initials.java.
8. Write a class that prompts a student for the number of credit hours in which the student is enrolled, and
the amount of money spent on books. Display, with a full explanation, the student’s total fees. The total is
$85 per credit hour, plus the amount for books, plus a $65 athletic fee. Save the class as Fees.java.
9. Write a class that accepts a user’s hourly rate of pay and the number of hours worked. Display the user’s
gross pay, the withholding tax (15% of gross pay), and the net pay (gross pay – withholding). Save the
class as Payroll.java.
10. Write a class that calculates and displays the conversion of an entered number of dollars into currency
denominations—20s, 10s, 5s, and 1s. Save the class as Dollars.java.
11. Write a program that accepts a temperature in Fahrenheit from a user and converts it to Celsius by
subtracting 32 from the Fahrenheit value and multiplying the result by 5/9. Display both values. Save the
class as FahrenheitToCelsius.java.
12. Travel Tickets Company sells tickets for airlines, tours, and other travel-related services. Because ticket
agents frequently mistype long ticket numbers, Travel Tickets has asked you to write an application
that indicates invalid ticket number entries. The class prompts a ticket agent to enter a six-digit ticket
number. Ticket numbers are designed so that if you drop the last digit of the number, then divide the
number by 7, the remainder of the division will be identical to the last dropped digit. This process is
illustrated in the following example:
Accept the ticket number from the agent and verify whether it is a valid number. Test the application with
the following ticket numbers:
123454; the comparison should evaluate to true
147103; the comparison should evaluate to true
154123; the comparison should evaluate to false
Save the program as TicketNumber.java.
Each of the following files in the Chapter.02 folder on your Student Disk has syntax and/or logic errors.
In each case, determine the problem and fix the application. After you correct the errors, save each file
using the same filename preceded with Fix. For example, DebugTwo1.java will become FixDebugTwo1.
Mad Libs® is a children’s game in which they provide a few words that are then incorporated into a silly
story. The game helps children understand different parts of speech because they are asked to provide
specific types of words. For example, you might ask a child for a noun, another noun, an adjective, and a
past-tense verb. The child might reply with such answers as “table,” “book,” “silly,” and “studied.” The
newly created Mad Lib might be:
Mary had a little
book was silly as snow
And everywhere that Mary
table was sure to go.
Create a Mad Lib program that asks the user to provide at least four or five words, and then create and
display a short story or nursery rhyme that uses them. Save the file as
Enter the ticket number; for example, 123454.
Remove the last digit, leaving 12345.
Determine the remainder when the ticket number is divided by 7. In this case, 12345
divided by 7 leaves a remainder of 4.
Assign the Boolean value of the comparison between the remainder and the digit
dropped from the ticket number.
Display the result—
—in a message box.
1. In a single sentence, describe the relationship between associativity and precedence.
2. Write Java statements that would round a numeric value to the nearest whole number. You cannot use a
prewritten round() method.
3. Suppose you need to display the last digit of a four-digit number. You can use the remainder operator (%) to
extract the remainder when the number is divided by 10. Suppose the “%” key is broken on your computer,
but the program must be written immediately. What would you do?
4. Write a series of Java statements that interchange the values of two numeric variables without using a third
5. In many programming languages, a named constant must be assigned a value when it is declared. This isn’t
true in Java. Provide some examples of how this restriction might be advantageous.
up For DisCussion
1. What advantages are there to requiring variables to have a data type?
2. Some programmers use a system called Hungarian notation when naming their variables. What is
Hungarian notation, and why do many object-oriented programmers feel it is not a valuable style to use?
What do you think?
3. Some languages do not require explicit type casting when you want to perform an unlike assignment, such
as assigning a double to an int. Instead, the type casting is performed automatically, the fractional part of
the double is lost, and the whole number portion is simply stored in the int result. Are there any reasons
this approach is superior or inferior to the way Java works? Which do you prefer?
4. Did you have a favorite computer game when you were growing up? Do you have one now? How are they
similar and how are they different? Did you have a favorite board game? What does it have in common
with your favorite computer game?
C h a p t e r t h r e e
using methoDs, Classes,
1. Create an application named TestMethods whose main() method holds two integer variables.
Assign values to the variables. In turn, pass each value to methods named displayIt(),
, and displayItPlusOneHundred(). Create each method to perform the
task its name implies. Save the application as TestMethods.java.
2. a. Create an application named Numbers whose main() method holds two integer variables. Assign
values to the variables. Pass both variables to methods named sum() and difference(). Create the
methods sum() and difference(); they compute the sum of and difference between the values of
two arguments, respectively. Each method should perform the appropriate computation and display
the results. Save the application as Numbers.java.
b. Add a method named product() to the Numbers class. The product() method should
compute the multiplication product of two integers, but not display the answer. Instead, it should
return the answer to the calling method, which displays the answer. Save the application as Numbers2.
3. Create a class named Eggs. Its main() method holds an integer variable named eggs to which
you will assign a value entered by a user at the keyboard. Create a method to which you pass eggs. The
method displays the eggs in dozens; for example, 50 eggs is 4 full dozen (with 2 eggs remaining). Save the
application as Eggs.java.
4. a. Create a class named Exponent. Its main() method accepts an integer value from a user at the
keyboard, and in turn passes the value to a method that squares the number (multiplies it by itself) and
to a method that cubes the number (multiplies it by itself twice). The main() method prints the results.
Create the two methods that, respectively, square and cube an integer that is passed to them, returning
the calculated value. Save the application as Exponent.java.