[go: up one dir, main page]

0% found this document useful (0 votes)
1K views64 pages

Answers To Review Questions: Starting Out With Java - From Control Structures Through Objects

This document contains answers to review questions from Chapter 1 of the book "Starting Out with Java: From Control Structures through Objects". It includes multiple choice questions with answers, examples of errors in code, algorithms to analyze, predictions of code output, and short answer explanations. Overall, it provides a high-level review of key concepts in the first chapter such as variables, data types, control structures, and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views64 pages

Answers To Review Questions: Starting Out With Java - From Control Structures Through Objects

This document contains answers to review questions from Chapter 1 of the book "Starting Out with Java: From Control Structures through Objects". It includes multiple choice questions with answers, examples of errors in code, algorithms to analyze, predictions of code output, and short answer explanations. Overall, it provides a high-level review of key concepts in the first chapter such as variables, data types, control structures, and more.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 1
Multiple Choice
1. b
2. d
3. a
4. c
5. b
6. b
7. c
8. d
9. a
10. b
11. a
12. c
13. b
14. d

Find the Error

1. The algorithm performs the math operation at the wrong time. It multiplies width
by length before getting values for those variables.

Algorithm Workbench

1. Display "What is the customer's maximum amount of credit?"


Input maxCredit.
Display "What is the amount of credit used by the customer?"
Input creditUsed.
availableCredit = maxCredit – creditUsed.
Display availableCredit.

2. Display "What is the retail price of the item?"


Input retailPrice.
Display "What is the sales tax rate?"
Input taxRate.
salesTax = retailPrice * taxRate.
total = retailPrice + salesTax.
Display salesTax.
Display total.

3. Display "What is the account's starting balance?"


Input startingBalance.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

Display "What is the total amount of the deposits made?"


Input deposits.
Display "What is the total amount of the withdrawals made?"
Input withdrawals.
Display "What is the monthly interest rate?"
Input interestRate.
balance = startingBalance + deposits – withdrawals.
interest = balance * interestRate.
balance = balance + interest.
Display balance.

Predict the Result

1. 7
2. 28

Short Answer

1. Main memory, or RAM, holds the sequences of instructions in the programs that
are running and the data those programs are using. Main memory, or RAM, is
usually volatile. Secondary storage is a type of memory that can hold data for
long periods of time—even when there is no power to the computer.
2. RAM is usually volatile.
3. An operating system is a set of programs that manages the computer’s hardware
devices and controls their processes. Windows and UNIX are examples of
operating systems. Application software refers to programs that make the
computer useful to the user. These programs solve specific problems or perform
general operations that satisfy the needs of the user. Word processing,
spreadsheet, and database packages are all examples of application software.
4. Because the computer is only capable of directly processing machine language
instructions.
5. Because machine language programs are streams of binary numbers, and high-
level language programs are made up of words.
6. A file that contains source code, which is the code written by the programmer.
7. Syntax errors are mistakes that the programmer has made that violate the rules of
the programming language. Logical errors are mistakes that cause the program to
produce erroneous results.
8. An algorithm is a set of well-defined steps for performing a task or solving a
problem.
9. A program that translates source code into executable code.
10. An application is a stand-alone program that runs on your computer. An applet is
designed to be transmitted over the Internet from a Web server, and then executed
in a Web browser.
11. Because the browser executes them in a restricted environment.
12. A Java Virtual Machine (JVM) program.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

13. Machine language code is executed directly by the CPU. Byte code is executed by
the JVM.
14. Because Java byte code is the same for all computers.
15. Object-oriented programming
16. When an object’s internal data is hidden from outside code and access to that data
is restricted to the object’s methods, the data is protected from accidental
corruption. In addition, the programming code outside the object does not need to
know about the format or internal structure of the object’s data. The code only
needs to interact with the object’s methods. When a programmer changes the
structure of an object’s internal data, he or she also modifies the object’s methods
so they may properly operate on the data. The way in which outside code interacts
with the methods, however, does not change.
17. The object's methods.
18. A text editor.
19. No
20. Byte code
21. javac LabAssignment.java
22.
a) LabAssignment.class
b) The byte code generated by the compiler.
c) java LabAssignment
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 2
Multiple Choice and True/False
1. c
2. b
3. a
4. b and c
5. a, c, and d
6. a
7. c
8. b
9. a
10. d
11. b
12. a
13. a
14. c
15. a
16. True
17. True
18. False
19. True
20. False
21. False

Predict the Output


1. 0
100
2. 8
2
3. I am the incrediblecomputing
machine
and I will
amaze
you.
4. Be careful
This might/n be a trick question.
5. 23
1

Find the Error


• The comment symbols in the first line are reversed. They should be /* and */.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

• The word class is missing in the second line. It should read public class
MyProgram.
• The main header should not be terminated with a semicolon.
• The fifth line should have a left brace, not a right brace.
• The first four lines inside the main method are missing their semicolons.
• The comment in the first line inside the main method should begin with forward
slashes (//), not backward slashes.
• The last line inside the main method, a call to println, uses a string literal, but
the literal is enclosed in single quotes. It should be enclosed in double quotes, like
this: "The value of c is".
• The last line inside the main method passes C to println, but it should pass c
(lowercase).
• The class is missing its closing brace.

Algorithm Workbench
1. double temp, weight, age;
2. int months = 2, days, years = 3;
3.
a) b = a + 2;
b) a = b * 4;
c) b = a / 3.14;
d) a = b – 8;
e) c = 'K';
f) c = 66;
4.
a) 12
b) 4
c) 4
d) 6
e) 1
5.
a) 3.287E6
b) -9.7865E12
c) 7.65491E-3
6.
System.out.print("Hearing in the distance\n\n\n");
System.out.print("Two mandolins like creatures in the\n\n\n");
System.out.print("dark\n\n\n");
System.out.print("Creating the agony of ecstasy.\n\n\n");
System.out.println(" - George Barker");
7. 10 20 1
8. 12
9. a
10. HAVE A GREAT DAY!
Have a great day!
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

11.
int speed, time, distance;
speed = 20;
time = 10;
distanct = speed * time;
System.out.println(distance);
12.
double force, area, pressure;
force = 172.5;
area = 27.5;
pressure = area / force;
System.out.println(pressure);

13.
double income;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Ask the user to enter his or her desired income
System.out.print("Enter your desired annual income: ");
income = keyboard.nextDouble();
14.
String str;
double income;
str = JOptionPane.showInputDialog("Enter your desired " +
"annual income.");
income = Double.parseDouble(str);

15. total = (float)number;

Short Answer
1. Multi-line style
2. Single line style
3. A self-documenting program is written in such a way that you get an
understanding of what the program is doing just by reading its code.
4. Java is a case sensitive language, which means that it regards uppercase letters as
being entirely different characters than their lowercase counterparts. This is
important to know because some words in a Java program must be entirely in
lowercase.
5. The print and println methods are members of the out object. The out
object is a member of the System class. The System class is part of the Java
API.
6. A variable declaration tells the compiler the variable’s name and the type of data
it will hold.
7. You should always choose names for your variables that give an indication of
what they are used for. The rather nondescript name, x, gives no clue as to what
the variable’s purpose is.
8. It is important to select a data type that is appropriate for the type of data that your
program will work with. Among the things to consider are the largest and smallest
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

possible values that might be stored in the variable, and whether the values will be
whole numbers or fractional numbers.
9. In both cases you are storing a value in a variable. An assignment statement can
appear anywhere in a program. An initialization, however, is part of a variable
declaration.
10. Comments that start with // are single-line style comments. Everything
appearing after the // characters, to the end of the line, is considered a comment.
Comments that start with /* are multi-line style comments. Everything between
these characters and the next set of */ characters is considered a comment. The
comment can span multiple lines.
11. Programming style refers the way a programmer uses spaces, indentations, blank
lines, and punctuation characters to visually arrange a program’s source code. An
inconsistent programming style can create confusion for a person reading the
code.
12. One reason is that the name PI is more meaningful to a human reader than the
number 3.14. Another reason is that any time the value that the constant
represents needs to be changed, we merely have to change the constant's
initialization value. We do not have to search through the program for each
statement that uses the value.
13. javadoc SalesAverage.java
14. The result will be an int.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 3
Multiple Choice and True/False

1. b
2. d
3. a
4. b
5. c
6. d
7. a
8. b
9. a
10. a
11. a
12. c
13. c
14. b
15. c
16. False
17. True
18. True
19. True
20. False
21. True

Find the Error

1. Each if clause is prematurely terminated by a semicolon.


2. The = operator should be ==.
3. The conditionally-executed blocks of code should be enclosed in braces.
4. The case expressions cannot have relational operators. They must be integer
expressions.
5. The ! operator is only applied to the variable x, not the expression. The code
should read:

if (!(x > 20))

6. The statement should use the && operator instead of the || operator.
7. The statement should use the || operator instead of the && operator.
8. The : and ? are reversed in their positions. The statement should read:
z = (a < 10) ? 0 : 7;
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

9. The equalsIgnoreCase method should be used instead of the equals


method.
10. The format specifier should be "%.2f" because the value variable is a
double.

Algorithm Workbench

1. if (y == 0)
x = 100;

2. if (y == 10)
x = 0;
else
x = 1;

3. if (sales < 10000)


commission = .10;
else if (sales <= 15000)
commission = .15;
else
commission = .20;

4. if (minimum)
hours = 10;

5. if (amount1 > 10)


{
if (amount2 < 100)
{
if (amount1 > amount2)
{
System.out.println(amount1);
}
else
{
System.out.println(amount2);
}
}
}

6. if (grade >= 0 && grade <= 100)


System.out.println("The number is valid.");

7. if (temperature >= -50 && temperature <= 150)


System.out.printn("The number is valid.");
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

8. if (hours < 0 || hours > 80)


System.out.println("The number is not valid.");

9. if (title1.compareTo(title2) < 0)
System.out.println(title1 + " " + title2);
else
System.out.println(title2 + " " + title1);

10. switch (choice)


{
case 1:
System.out.println("You selected 1.");
break;
case 2:
case 3:
System.out.println("You selected 2 or 3.");
break;
case 4:
System.out.println("You selected 4.");
break;
default:
System.out.println("Select again please.");

11. C, A, B
12. System.out.printf("%.1f", number);
13. System.out.printf("%,.2f", number);
14. System.out.printf("%,d", number);
15. "00000.000"
16. "000,000,000.00"

Short Answer

1. Conditionally executed code is executed only under a condition, such as an


expression being true.
2. If you inadvertently terminate an if statement with a semicolon, the compiler
will assume that you are placing a null statement there. The null statement, which
is an empty statement that does nothing, will become the conditionally executed
statement. The statement that you intended to be conditionally executed will be
disconnected from the if statement and will always execute.
3. By indenting the conditionally executed statements, you are causing them to stand
out visually. This is so you can tell at a glance what part of the program the if
statement executes.
4. The memory addresses of the two String objects are compared.
5. A flag is a boolean variable that signals when some condition exists in the
program. When the flag variable is set to false, it indicates the condition does not
yet exist. When the flag variable is set to true, it means the condition does exist.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

6. There is no default action that takes place when none of the if clauses'
boolean expressions are true.
7. It takes two boolean expressions as operands and creates a boolean expression
that is true only when both subexpressions are true.
8. It takes two boolean expressions as operands and creates a boolean expression
that is true when either of the subexpressions are true.
9. They determine whether a specific relationship exists between two values. The
relationships are greater-than, less-than, equal-to, not equal-to, greater-than or
equal-to, and less-than or equal-to.
10. A constructor executes automatically when an object is created. Its purpose is to
initialize the object's attributes with data and perform any necessary startup
operations.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 4
Multiple Choice and True/False

1. a
2. b
3. c
4. d
5. a
6. a
7. b
8. a
9. c
10. b
11. a
12. d
13. a
14. a
15. d
16. b
17. d
18. b
19. True
20. False
21. False
22. False
23. False
24. True
25. True
26. False

Find the Error

1. The conditionally-executed statements should be enclosed in a set of braces.


Also, the again variable should be initialized with either 'y' or 'Y'.
2. The while loop is an infinite loop because it does nothing to change the value of
count.
3. The expression being tested by the do-while loop should be choice == 1.
Also, the do-while loop must be terminated by a semicolon.
4. The initialization and test expressions should be terminated with semicolons, not
commas. Also, the statement count++; should not appear inside the body of the
loop.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

Algorithm Workbench

1. Scanner keyboard = new Scanner(System.in);


int product = 0, num;
while (product < 100)
{
num = keyboard.nextInt();
product = num * 10;
}

2. char again;
String input;
Scanner keyboard = new Scanner(System.in);
do
{
double num1, num2;
System.out.print("Enter a number: ");
num1 = keyboard.nextDouble();
System.out.print("Enter another number: ");
num2 = keyboard.nextDouble();
System.out.println("Their sum is " +
(num1 + num2));
System.out.print("Do you wish to do this " +
"again? (Y/N) ");
input = keyboard.readLine();
again = input.charAt(0);;
} while (again == 'Y' || again == 'y');

3. The following code simply prints the numbers, separated by spaces.


for (int x = 0; x <= 1000; x += 10)
System.out.print(x + " ");

The following code prints the numbers separated by commas.


for (int x = 0; x <= 1000; x += 10)
{
if (x < 1000)
System.out.print(x + ", ");
else
System.out.print(x);
}

4. Scanner keyboard = new Scanner(System.in);


double total = 0.0, num;
for (int count = 0; count < 10; count++)
{
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

System.out.print("Enter a number: ");


num = keyboard.nextDouble();
total += num;
}
System.out.println("The total is " + total);

5. double total = 0;
for (int num = 1, denom = 30; num <= 30; num++, denom--)
total += num / denom;

6. for (int row = 0; row < 10; row++)


{
for (int col = 0; col < 15; col++)
System.out.print('#');
System.out.println();
}

7. Scanner keyboard = new Scanner(System.in);


int x;
do
{
System.out.print("Enter a number: ");
x = keyboard.nextInt();
} while (x > 0);

8. Scanner keyboard = new Scanner(System.in);


String input;
char sure = 'x';
while (sure != 'Y' && sure != 'N')
{
System.out.print("Are you sure you want quit? ");
input = keyboard.nextLine();
sure = input.charAt(0);
}

9. for (int count = 0; count > 50; count++)


System.out.println("count is " + count);

10. int x = 50;


while (x > 0)
{
System.out.println(x + " seconds to go.");
x--;
}

11. int number;


Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

Scanner keyboard = new Scanner(System.in);


System.out.print("Enter a number in the range " +
"of 1 through 4: ");
number = keyboard.nextInt();
while (number < 1 || number > 4)
{
System.out.print("Invalid number. Enter a " +
"number in the range " +
"of 1 through 4: ");
number = keyboard.nextInt();
}

12. Scanner keyboard = new Scanner(System.in);


String input;
System.out.print("Enter yes or no: ");
input = keyboard.nextLine();
while (!input.equals("yes") && !input.equals("no"))
{
System.out.print("Invalid input. " +
"Enter yes or no: ");
input = keyboard.nextLine();
}

13.
for (int r = 7; r > 0; r--)
{
for (int c = 0; c < r; c++)
{
System.out.print("*");
}
System.out.println();
}
14.
for (int r = 0; r < 6; r++)
{
System.out.print("#");
for (int c = 0; c < r; c++)
{
System.out.print(" ");
}
System.out.println("#");
}

15.
import java.util.Random;

public class ReviewQuestion15


Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 5

{
public static void main(String[] args)
{
Random rand = new Random();
System.out.println(rand.nextInt(10) + 1);
}
}

16.
import java.util.Random;

public class ReviewQuestion16


{
public static void main(String[] args)
{
Random rand = new Random();
for (int count = 0; count < 10; count++)
{
if (rand.nextInt(2) == 0)
System.out.println("Yes");
else
System.out.println("No");
}

}
}

17.
PrintWriter outFile =
new PrintWriter("NumberList.txt");

for (int i = 1; i <= 100; i++)


outFile.println(i);
outFile.close();

18.
File file = new File("NumberList.txt");
Scanner inFile = new Scanner(file);
while (inFile.hasNext())
{
int number = inFile.nextInt();
System.out.println(number);
}
inFile.close();

19.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 6

File file = new File("NumberList.txt");


Scanner inFile = new Scanner(file);
int total = 0;
while (inFile.hasNext())
{
int number = inFile.nextInt();
total += number;
}
inFile.close();
System.out.println("The total is " + total);

20.
FileWriter fwriter =
new FileWriter("NumberList.txt", true);
PrintWriter outFile = new PrintWriter(fwriter);

Short Answer

1. In postfix mode the operator is placed after the operand. In prefix mode the
operator is placed before the variable operand. Postfix mode causes the increment
or decrement operation to happen after the value of the variable is used in the
expression. Prefix mode causes the increment or decrement to happen first.
2. A pretest loop tests its condition before each iteration. A posttest loop tests its
condition after each iteration. A posttest loop will always execute at least once.
3. A pretest loop tests its test expression before each iteration. A posttest loop tests
its test expression after each iteration.
4. Because the loop executes them only under the condition that its test expression is
true.
5. The while loop is a pretest loop and the do-while loop is a posttest loop.
6. The while loop.
7. The do-while loop.
8. The for loop.
9. An accumulator is used to keep a running total of numbers. In a loop, a value is
usually added to the current value of the accumulator. If it is not properly
initialized, it will not contain the correct total.
10. A loop that has no way of stopping. Here is an example:
int x = 1;
while (x > 0)
System.out.println("Hello");
11. There are many possible examples. A program that asks the user to enter a
business's daily sales for a number of days, and then displays the total sales is one
example.
12. The loop terminates after the user has entered a specific value.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 7

13. Sometimes the user has a list of input values that is very long, and doesn’t know
the number of items there are. When the sentinel value is entered, it signals the
end of the list, and the user doesn't have to count the number of items in the list.
14. So it cannot be mistaken as a member of the list.
15. There are many possible examples. One example is a program that asks for the
average temperature for each month, for a period of five years. The outer loop
would iterate once for each year and the inner loop would iterate once for each
month.
16. When a program writes data to a file, that data is first written to the buffer. When
the buffer is filled, all the information stored there is written to the file. This
technique increases the system’s performance because writing data to memory is
faster than writing it to a disk.
17. Closing a file writes any unsaved data remaining in the file buffer.
18. The read position is the position of the next item to be read. When the file is
opened, its read position is set to the first item in the file.
19. After the println method writes its data, it writes a newline character. The
print method does not write the newline character.
20. false
21. The file does not exist.
22. To write the data to the end of the file's existing contents.
23. You create an instance of the FileWriter class to open the file. You pass the
name of the file (a string) as the constructor's first argument, and the boolean
value true as the second argument. Then, when you create an instance of the
PrintWriter class, you pass a reference to the FileWriter object as an
argument to the PrintWriter constructor. The file will not be erased if it
already exists and new data will be written to the end of the file.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 5
Multiple Choice and True/False
1. b
2. d
3. a
4. e
5. b
6. a
7. b
8. d
9. c
10. False
11. True
12. False
13. False
14. False
15. True
16. True
17. False
18. False
19. False
20. True

Find the Error


1. The header should not be terminated with a semicolon.
2. The int data type should not be listed in the method call. The statement should read:
showValue(x);
3. The method should have a return statement that returns a double value.
4. The method's return type should be double instead of int.

Algorithm Workbench
1. doSomething(25);
2.
a) This statement will compile successfully.
b) This statement will cause an error because 6.5 cannot be automatically
converted to an int.
c) This statement will compile successfully.
d) This statement will cause an error because a long cannot be automatically
converted to an int.
e) This statement will cause an error because the float value 6.2 cannot be
automatically converted to an int.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

f) This statement will compile successfully.

3. The value 3 will be stored in a, 2 will be stored in b, and 1 will be stored in c.


4.
1 3.4
0 0.0
1 3.4

5. result = cube(4);
6. display(age, income, initial);
7.
public static double timesTen(double num)
{
return num * 10.0;
}

8.
public static int square(int num)
{
return num * num;
}

9.
// Assume java,util.Scanner has been imported.
public static String getName()
{
String name;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your first name: ");
name = keyboard.nextLine();
return name;
}

10.
public static double quartersToDollars(int quarters)
{
double dollars = quarters * 0.25;
return dollars;
}

Short Answer
1. A large complex problem is broken down into smaller manageable pieces. Each
smaller piece of the problem is then solved.
2. A void method does not return a value back to the statement that called it, and a
value-returning method does.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

3. An argument is a value that is passed into a method when the method is called. A
parameter variable is a variable that is declared in the method header, and receives
the value of an argument when the method is called.
4. In the method header, between the parentheses.
5. When an argument is passed to a method, only a copy of the argument is passed.
The method cannot access the actual argument.
6. Because they are destroyed in memory when the method ends execution.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 6
Multiple Choice and True/False

1. a
2. b
3. d
4. c
5. b
6. a
7. d
8. b
9. b
10. a
11. c
12. c
13. b
14. d
15. True
16. True
17. False
18. False
19. False

Find the Error

1. The constructor cannot have a return type, not even void.


2. The method should have int as its return type.
3. The parentheses are missing. The statement should read:
Rectangle box = new Rectangle();
4. The constructors must have different parameter lists. Both are empty.
5. The square methods must have different parameter lists. Both accept an int.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

Algorithm Workbench

1.
a) UML diagram:

b) Class code:

public class Pet


{
private String name; // The pet's name
private String animal; // The type of animal
private int age; // The pet's age

/**
setName method
@param n The pet's name.
*/

public void setName(String n)


{
name = n;
}

/**
setAnimal method
@param a The type of animal.
*/

public void setAnimal(String a)


{
animal = a;
}

/**
setAge method
@param a The pet's age.
*/
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

public void setAge(int a)


{
age = a;
}

/**
getName method
@return The pet's name.
*/

public String getName()


{
return name;
}

/**
getAnimal method
@return The type of animal.
*/

public String getAnimal()


{
return animal;
}

/**
getAge method
@return The pet's age.
*/

public int getAge()


{
return age;
}
}

2.
a) Constructor:

public Book(String t, String a, String p, int c)


{
title = t;
author = a;
publisher = p;
copiesSold = c;
}

b) Accessor and mutator methods

public void setTitle(String t)


{
title = t;
}
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

public void setAuthor(String a)


{
author = a;
}

public void setPublisher(String p)


{
publisher = p;
}

public void setCopiesSold(int c)


{
copiesSold = c;
}

public String getTitle()


{
return title;
}

public String getAuthor()


{
return author;
}

public String getPublisher()


{
return publisher;
}

public int getCopiesSolde()


{
return copiesSold;
}
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 5

c) UML diagram:

3.
a)
public Square()
{
sideLength = 0.0;
}

b)
public Square(double s)
{
sideLength = s;
}

4. a) After eliminating duplicates, objects, and primitive values, the potential


classes are: bank, account, and customer
b) The only class needed for this particular problem is account.
c) The account class knows its balance and interest rate.
The account can calculate interest earned.

Short Answer

1. A class is a collection of programming statements that specify the attributes and


methods that a particular type of object may have. You should think of a class as a
“blueprint” that describes an object. An instance of a class is an actual object that
exists in memory.
2. Classes are analogous to the blueprint.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 6

3. An accessor method is a method that gets a value from a class’s field but does not
change it. A mutator method is a method that stores a value in a field or in some
other way changes the value of a field.
4. When an object’s fields are hidden from outside code, the fields are protected
from accidental corruption. It is good idea to make all of a class’s fields private
and to provide access to those fields through methods.
5. Methods that are members of the same class.
6. It creates an object (an instance of a class) in memory.
7. It looks in the current folder or directory for the file Customer.class. If that
file does not exist, the compiler searches for the file Customer.java and
compiles it. This creates the file Customer.class, which makes the
Customer class available. The same procedure is followed when the compiler
searches for the Account class.
8. Because they execute when an object is created.
9. If you do not write a constructor for a class, Java automatically provides one.
10. A no-arg constructor.
11. By their signatures, which includes the method name and the data types of the
method parameters, in the order that they appear.
12. Several different versions of the same method can be created, each performing an
operation in a different manner. This makes the class more flexible.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 7
Multiple Choice and True/False

1. b
2. a
3. b
4. d
5. c
6. c
7. b
8. a
9. d
10. a
11. c
12. a
13. a
14. True
15. False
16. True
17. True
18. True
19. True
20. True
21. False
22. True
23. True

Find the Error

1. The size declarator cannot be negative.


2. The initialization list must be enclosed in braces.
3. The loop uses the values 1 through 10 as subscripts. It should use 0 through 9.
4. With an array, length is a field. With a String, length is a method. This
code uses length as if it were a method in the array, and a field in the String.
5. A subscript should be used with words, such as words[0].toUpperCase().

Algorithm Workbench

1. for (int i = 0; i < 20; i++)


System.out.println(names[i]);

2. for (int i = 0; i < 100; i++)


Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

numberArray2[i] = numberArray1[i];

3.
a) String[] scientists = {"Einstein", "Newton",
"Copernicus", "Kepler"};
b) for (int i = 0; i < scientists.length; i++)
System.out.println(scientists[i]);
c) int total = 0;
for (int i = 0; i < scientists.length; i++)
total += scientists[i].length();
System.out.println("The total length is " + total);

4.
a)
// Define the arrays.
final int NUM_COUNTRIES = 12;
String[] countries = new String[NUM_COUNTRIES];
long[] populations = new long[NUM_COUNTRIES];

b)
// Display their contents.
for (int i = 0; i < NUM_COUNTRIES; i++)
{
System.out.println("The population of " + countries[1] +
" is " + populations[i]);
}

5.
a)
// Define the arrays.
int[] id = new int[10];
double[] weeklyPay = new double[10];

b)
// Display each employee's gross weekly pay.
for (int i = 0; i < 10; i++)
{
System.out.println("The pay for employee " +
id[i] + " is $" +
weeklyPay[i]);
}

6. final int NUM_ROWS = 30;


final int NUM_COLS = 10;
int[][] grades = new int[NUM_ROWS][NUM_COLS];

7. final int NUM_ROWS = 30;


final int NUM_COLS = 10;
int total = 0;
double average;
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

for (int row = 0; row < grades.length; row++)


{
for (int col = 0; col < grades[row].length; col++)
{
total += grades[row][col];
}
}
average = (double) total / (NUM_ROWS * NUM_COLS);

8. a) numberArray[0][0] = 145;
b) numberArray[8][10] = 18;

9. double total = 0.0; // Accumulator


// Sum the values in the array.
for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 20; col++)
total += values[row][col];
}

10.
a) Sum each row in the array:

int total; // Accumulator


// Display the sum of each row.
for (int row = 0; row < 29; row++)
{
// Set the accumulator.
total = 0;
// Sum a row.
for (int col = 0; col < 5; col++)
total += days[row][col];
// Display the row's total.
System.out.println("The total for row " + row +
" is " + total);
}

b) Sum each column in the array:

// Display the sum of each column.


for (int col = 0; col < 5; col++)
{
// Set the accumulator.
total = 0;

// Sum a column.
for (int row = 0; row < 29; row++)
total += days[row][col];
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

// Display the column's total.


System.out.println("Column total: " + total);
}

11. // Create an ArrayList.


ArrayList<String> cars = new ArrayList<String>();
// Add three car names to the ArrayList.
cars.add("Porsche");
cars.add("BMW");
cars.add("Jaguar");
// Display the contents of cars.
for (String str : cars)
System.out.println(str);

Short Answer

1. The size declarator is used in a definition of an array to indicate the number of


elements the array will have. A subscript is used to access a specific element in an
array.
2. a) The array has 10 elements.
b) The subscript of the first element is 0.
c) The subscript of the last element is 9.
3. a) 2
b) 14
c) 8
4. By providing an initialization list. The array is sized to hold the number of values
in the list.
5. Because this statement merely makes array1 reference the same array that
array2 references. Both variables will reference the same array. To copy the
contents of array2 to array1, the contents of array2's individual elements
will have to be assigned to the elements of array1.
6. By using the same subscript value for each array.
7. Yes, the statements are okay.
8. It will have to read all 10,000 elements to find the value stored in the last element.
9. a) Eight rows
b) Ten columns
c) Eighty elements
d) sales[7][9] = 123.45;
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 8
Multiple Choice and True/False

1. c
2. c
3. a
4. c
5. b
6. c
7. d
8. b
9. c
10. a
11. b
12. False
13. False
14. True
15. False

Find the Error

1. The static method setValues cannot refer to the non-static fields x and y.
2. You cannot use the fully-qualified names of enum constants in the case
expressions.

Algorithm Workbench

1.

a) public String toString()


{
String str;
str = "Radius: " + radius +
" Area: " + getArea();
return str;
}

b) public boolean equals(Circle c)


{
boolean status;

if (c.getRadius() == radius)
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

status = true;
else
status = false;

return status;
}

c) public boolean greaterThan(Circle c)


{
boolean status;

if (c.getArea() > getArea())


status = true;
else
status = false;

return status;
}

2.
a) 3
b) 3
c) 1
d) 0
e) Thing.putThing(5);

3. enum Pet { DOG, CAT, BIRD, HAMSTER }

Short Answer

1. Access a non-static member.


2. They can be called directly from the class, as needed. They can be used to create
utility classes that perform operations on data, but have no need to collect and
store data.
3. When a variable is passed as an argument, a copy of the variable's contents is
passed. The receiving method does not have access to the variable itself. When an
object is passed as an argument, a reference to the object (which is the object's
address) is passed. This allows the receiving method to have access to the object.
4. The default equals method returns true if the memory addresses of the two
objects being compared are the same.
5. It means that an aggregate relationship exists. When an object of class B is a
member of class A, it can be said that class A "has a" class B object.
6. The program will crash.
7. It is not advisable because it will allow access to the private fields. The exception
to this is when the field is a String object. This is because String objects are
immutable, meaning that they cannot be changed.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

8. The key word this is the name of a reference variable that an object can use to
refer to itself. It is available to all non-static methods.
9. a) Color
b) Color.RED, Color.ORANGE, Color.GREEN, Color.BLUE
c) Color myColor = Color.BLUE;
10. a) POODLE
BOXER
TERRIER
b) 0
1
2
c) BOXER is NOT greater than TERRIER

11. When there are no references to it.


Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 9
Multiple Choice and True/False

1. c
2. b
3. a
4. a
5. a
6. c
7. b
8. a
9. d
10. b
11. a
12. c
13. d
14. a
15. False
16. True
17. False
18. True
19. True
20. False
21. True
22. False
23. False

Find the Error

1. The valueOf method is static. It should be called like this:


str = String.valueOf(number);
2. You cannot initialize a StringBuilder object with the = operator. You must
pass the string as an argument to the constructor, such as:
StringBuilder name = new StringBuilder("Joe Schmoe");
3. The very first character is at position 0, so the statement should read:
str.setCharAt(0, 'Z');
4. If anything other than whitespace is to be used as a delimiter, then the delimiter
must be passed as an argument to the StringTokenizer constructor, such as:
StringTokenizer strTokenizer =
new StringTokenizer("One;Two;Three", ";");
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

Algorithm Workbench

1. if (Character.toUpperCase(choice) == 'Y')

Or

if (Character.toLowerCase(choice) == 'y')

2. int total = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ' ')
total++;
}

3. int total = 0;
for (int i = 0; i < str.length(); i++)
{
if (Character.isDigit(str.charAt(i)))
total++;
}

4. int total = 0;
for (int i = 0; i < str.length(); i++)
{
if (Character.isLowerCase(str.charAt(i)))
total++;
}

5. public static boolean dotCom(String str)


{
boolean status;
if (str.endsWith(".com"))
status = true;
else
status = false;
return status;
}

6. public static boolean dotCom(String str)


{
boolean status;
String str2 = str.toLowerCase();

if (str2.endsWith(".com"))
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

status = true;
else
status = false;
return status;
}

7. public static void upperT(StringBuilder str)


{
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == 't')
str.setCharAt(i, 'T');
}
}

8. a)
String str = "cookies>milk>fudge:cake:ice cream";
StringTokenizer strTok =
new StringTokenizer(str, ">:");
while (strTok.hasMoreTokens())
{
System.out.println(strTok.nextToken());
}
b)
String str = "cookies>milk>fudge:cake:ice cream";
String[] strTok = str.split("[>:]");
for (int i = 0; i < strTok.length; i++)
{
System.out.println(strTok[i]);
}

9. if (d <= Integer.MAX_VALUE)
i = (int) d;

10. System.out.println(Integer.toBinaryString(i));
System.out.println(Integer.toHexString(i));
System.out.println(Integer.toOctalString(i));

Short Answer

1. This will improve the program’s efficiency by reducing the number of String
objects that must be created and then removed by the garbage collector.
2. When you are tokenizing a string that was entered by the user, and you are using
characters other than whitespaces as delimiters, you will probably want to trim the
string before tokenizing it. Otherwise, if the user enters leading whitespace
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

characters, they will become part of the first token. Likewise, if the user enters
trailing whitespace characters, they will become part of the last token.
3. Converts a number to a string.
4. Each of the numeric wrapper classes has final static fields named MAX_VALUE
and MIN_VALUE. These fields hold the maximum and minimum values for the
data type.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 10
Multiple Choice and True/False

1. b
2. c
3. d
4. b
5. a
6. a
7. c
8. b
9. a
10. c
11. a
12. d
13. c
14. b
15. c
16. a
17. c
18. True
19. True
20. False
21. False
22. True
23. False
24. False
25. True
26. False
27. True
28. False
29. True

Find the Error

1. The Car class header should use the word extends instead of expands.
2. The Car class constructor cannot access the Vehicle class's cost field.
3. Because the Vehicle class does not have a default constructor or a no-arg
constructor, the Car class constructor must call the Vehicle class constructor.
4. The getMilesPerGallon method in the Car class should return a double.

Algorithm Workbench
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

1. public class Poodle extends Dog


2. Felis, then Tiger
3.
public abstract class B
{
private int m;
protected int n;

public void setM(int value)


{
m = value;
}

public void setN(int value)


{
n = value;
}

public int getM()


{
return m;
}

public int getN()


{
return n;
}

public abstract double calc();


}

public class D extends B


{
private double q;
protected double r;

public void setQ(double value)


{
q = value;
}

public void setR(double value)


{
r = value;
}
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

public double getQ()


{
return q;
}

public double getR()


{
return r;
}

public double calc()


{
return q * r;
}
}

4. super(x, y, z);
5. setValue(10);

Or

super.setValue(10);

6.
public int getValue()
{
return value;
}

7. public class Stereo extends SoundSystem


implements CDPlayable,
TunerPlayable,
CassettePlayable

8.
public interface Nameable
{
void setName(String n);
String getName();
}

Short Answer

1. When an “is a” relationship exists between objects, it means that the specialized
object has all of the characteristics of the general object, plus additional
characteristics that make it special.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

2. The superclass is Animal and the subclass is Dog.


3. Dog is the superclass and Pet is the subclass.
4. A protected member of a class may be directly accessed by methods of the same
class or methods of a subclass. In addition, and this is how protected members are
different from private members, protected members may be accessed by methods
of any class that are in the same package as the protected member’s class. A
protected member is not quite private, because it may be accessed by some
methods outside the class.
5. No.
6. The superclass.
7. Overloading is when a method has the same name as one or more other methods,
but a different parameter list. Although overloaded methods have the same name,
they have different signatures. When a method overrides another method,
however, they both have the same signature.
8. A superclass reference variable can reference objects of classes that inherit from
the superclass.
9. At runtime.
10. An abstract method is a method that appears in a superclass, but expects to be
overridden in a subclass. An abstract method has only a header and no body.
11. An abstract class is not instantiated itself, but serves as a superclass for other
classes. The abstract class represents the generic or abstract form of all the classes
that inherit from it.
12. A class can inherit from only one superclass, but Java allows a class to implement
multiple interfaces.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 11
Multiple Choice and True/False

1. b
2. c
3. a
4. d
5. b
6. a
7. d
8. b
9. c
10. b
11. c
12. b
13. d
14. a
15. c
16. a
17. True
18. False
19. False
20. False
21. True
22. True
23. False
24. False

Find the Error

1. The try block must appear first.


2. The finally block must appear after the catch blocks.
3. The catch (Exception e) statement and its block should appear after the
other catch blocks, because this is a more general exception than the others.

Algorithm Workbench

1.
B
D

2.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

B
D
E

3.
public static int arraySearch(int[] array, int value)
throws Exception
{
int i; // Loop control variable
int element; // Element the value is found at
boolean found; // Flag indicating search results

// Element 0 is the starting point of the search.


i = 0;

// Store the default values element and found.


element = -1;
found = false;

// Search the array.


while (!found && i < array.length)
{
if (array[i] == value)
{
found = true;
element = i;
}
i++;
}

if (element == -1)
throw new Exception("Element not found.");
else
return element;
}

4. throw new IllegalArgumentException("Argument cannot " +


"be negative.");

5.
public class NegativeNumber extends Exception
{
/**
No-arg constructor
*/

public NegativeNumber()
{
super("Error: Negative number");
}

/**
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

The following constructor accepts the number that


caused the exception.
@param n The number.
*/
public NegativeNumber(int n)
{
super("Error: Negative number: " + n);
}
}

6.
throw new NegativeNumber();
Or
throw new NegativeNumber(number);

7. public int getValueFromFile() throws IOException,


FileNotFoundException

8.
try
{
value = getValueFromFile();
}
catch (FileNotFoundException e)
{
System.out.println(e.getMesssage());
}
catch (IOException e)
{
System.out.println(e.getMesssage());
}

9. FileOutputStream fstream =
new FileOutputStream("Configuration.dat");

10. RandomAccessFile randomFile =


new RandomAccessFile("Customers.dat", "rw");

11.
FileOutputStream outStream =
new FileOutputStream("ObjectData.dat");
ObjectOutputStream objectOutputFile =
new ObjectOutputStream(outStream);
objectOutputFile.writeObject(r);

Short Answer
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

1. An exception object has been created in response to an error that has occurred.
2. The program intercepts the exception and responds to it.
3. Control of the program is passed to the previous method in the call stack (that is,
the method that called the offending method). If that method cannot handle the
exception, then control is passed again, up the call stack, to the previous method.
This continues until control reaches the main method. If the main method does
not handle the exception, then the program is halted and the default exception
handler handles the exception.
4. The finally statement's block is always executed after the try block has
executed and after any catch blocks have executed if an exception was thrown.
The statements in the finally block execute whether an exception occurs or not.
5. The first statement after that try/catch construct.
6. Yes. When in the same try statement you are handling multiple exceptions and
some of the exceptions are related to each other through inheritance, then you
should handle the more specialized exception classes before the more general
exception classes. Otherwise, a catch statement designed to catch a general
exception might catch a more specialized exception through polymorphism.
7. Any object that inherits from the Throwable class.
8. When the code in a method can potentially throw a checked exception and the
method doesn't handle the exception, then that method must have a throws
clause.
9. Unchecked exceptions are those that inherit from the Error class or the
RuntimeException class. You should not handle these exceptions because
the conditions that cause them can rarely be dealt with within the program. All of
the remaining exceptions (that is, those that do not inherit from Error or
RuntimeException) are checked exceptions. These are the exceptions that
you should handle in your program.
10. The throw statement causes an exception to be thrown. The throws clause
informs the compiler that a method throws one or more exceptions.
11. All of the data stored in a text file is formatted as text. Even numeric data is
converted to text when it stored in a text file. You can view the data stored in a
text file by opening it with a text editor, such as Notepad. In a binary file, data is
not formatted as text. Subsequently, you cannot view a binary file’s contents with
a text editor.
12. With sequential access, when a file is opened for input, its read position is at the
very beginning of the file. This means that the first time data is read from the file,
the data will be read from its beginning. As the reading continues, the file’s read
position advances sequentially through the file’s contents. In random file access, a
program may immediately jump to any location in the file without first reading
the preceding bytes. The difference between sequential and random file access is
like the difference between a cassette tape and a compact disc. When listening to
a CD, there is no need to listen to or fast-forward over unwanted songs. You
simply jump to the track that you want to listen to.
13. When an object is serialized it is converted to a series of bytes which are written
to a file. When the object is deserialized, the series of bytes are converted back
into an object.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 5
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 12
Multiple Choice and True/False
1. c
2. a
3. c
4. a
5. d
6. a
7. b
8. c
9. b
10. d
11. a
12. True
13. False
14. False
15. True
16. True
17. False
18. False
19. False
20. True

Find the Error


1. The x is missing in the package name. The statement should read:
import javax.swing.*;

2. The actionPerformed method must have an ActionEvent parameter.

3. The arguments passed to the GridLayout constructor are reversed. This


statement creates 10 rows and 5 columns.

4. The second argument passed to the add method should be


BorderLayout.NORTH.

5. You do not create an instance of BorderFactory. Instead you call one of its
static methods to create a Border object. The statement should read:

panel.setBorder(BorderFactory.createTitledBorder("Choices"));
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

Algorithm Workbench

1. myWindow.setSize(500, 250);

2. myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

3. myWindow.setVisible(true);

4. myButton.setBackground(Color.white);
myButton.setForeground(Color.red);

5. setLayout(new FlowLayout(FlowLayout.LEFT));

6. setLayout(new GridLayout(5, 10));

7. panel.add(button, BorderLayout.WEST);

8.
// Create three radio buttons.
JRadioButton radio1 = new JRadioButton("Option 1", true);
JRadioButton radio2 = new JRadioButton("Option 2");
JRadioButton radio3 = new JRadioButton("Option 3");
// Create a ButtonGroup object.
ButtonGroup group = new ButtonGroup();
// Add the radio buttons to the ButtonGroup object.
group.add(radio1);
group.add(radio2);
group.add(radio3);

9. panel.setBorder(BorderFactory.createLineBorder(Color.blue, 2));

Short Answer
1. The window is hidden from view, but the application does not end.
2. This prevents the component from being resized. The BorderLayout manager
resizes components to fill up any extra space in a region. When you place a
component inside a panel, and then place the panel in a BorderLayout region,
the panel is resized instead of the component it contains.
3. Radio buttons are normally used to select one of several possible items. Because a
mutually-exclusive relationship usually exists between radio buttons, only one of
the items may be selected. Check boxes, which may appear alone or in groups,
allow the user to make yes/no or on/off selections. Because there is not usually a
mutually-exclusive relationship between check boxes, the user can select any
number of them when they appear in a group.
4. By creating a class that is derived from JPanel.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 13
Multiple Choice and True/False
1. d
2. c
3. b
4. d
5. a
6. c
7. c
8. a
9. b
10. d
11. c
12. a
13. a
14. c
15. b
16. d
17. a
18. c
19. b
20. c
21. a
22. True
23. False
24. True
25. False
26. False
27. True
28. True
29. True
30. False
31. True
32. True
33. False
34. False
35. True

Find the Error


1. The argument false should have been passed to the setEditable method.
2. The code should read:
list.setBorder(BorderFactory.createLineBorder(Color.black, 1));
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

3. You should pass list as an argument to the JScrollPane constructor:


JScrollPane scrollPane = new JScrollPane(list);

4. The statement should read:


String selectedName = (String) nameBox.getSelectedItem();

5. The second statement should read:


label.setIcon(image);

6. You pass a JMenu object as an argument to the JMenuBar object's add


method:
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);

7. The statement should read:


JTextArea textArea = new JTextArea (5, 20);

Algorithm Workbench
1.
JTextField textField = new JTextField(20);
textField.setEditable(false);

2.
String[] days = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday",
"Sunday" };
JList dayList = new JList(days);

3.
dayList.setVisibleRowCount(4);
JScrollPane scrollPane = new JScrollPane(dayList);

4.

selection = (String) myList.getSelectedValue();

5.

selectionIndex = myComboBox.getSelectedIndex();

6. ImageIcon image = new ImageIcon("dog.jpg");


JLabel label = new JLabel(image);

7. ImageIcon image = new ImageIcon("picture.gif");


label.setIcon(image);
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

8. JButton openButton = new JButton("Open File");


openButton.setMnemonic(KeyEvent.VK_O);
openButton.setToolTipText("This button opens a file");

9. JFileChooser fileChooser = new JFileChooser();


int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
String filename = selectedFile.getPath();
}

10.
JTextArea textInput = JTextArea(10, 15);
JScrollPane scrollPane = new JScrollPane(textInput);
textInput.setLineWrap(true);
textInput.setWrapStyleWord(true);

11.

// Create an Open menu item.


JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic(KeyEvent.VK_O);
openItem.addActionListener(new OpenListener());

// Create a Print menu item.


JMenuItem printItem = new JMenuItem("Print");
printItem.setMnemonic(KeyEvent.VK_P);
printItem.addActionListener(new PrintListener());

// Create an Exit menu item.


JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.addActionListener(new ExitListener());

// Create a JMenu object for the File menu.


JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);

// Add the menu items to the File menu.


fileMenu.add(openItem);
fileMenu.add(printItem);
fileMenu.add(exitItem);

// Create the menu bar.


JMenuBar menuBar = new JMenuBar();
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

// Add the file menu to the menu bar.


menuBar.add(fileMenu);

// Set the window's menu bar.


setJMenuBar(menuBar);

12.
JSlider slider = new JSlider(JSlider.HORIZONTAL,
0, 1000, 500);
slider.setMajorTickSpacing(100);
slider.setMinorTickSpacing(25);
slider.setPaintTickMarks(true);
slider.setPaintLabels(true);

Short Answer
1. Single selection mode
2. JComboBox
3. An uneditable combo box combines a button with a list, and allows the user to
only select items from its list. An editable combo box combines a text field and a
list. In addition to selecting items from the list, the user may also type input into
the text field. The default type of combo box is uneditable.
4. You can pass the text as an argument to the constructor, and then pass an
ImageIcon object to the setIcon method. Another way is to pass the text, an
ImageIcon object, and an int specifying horizontal alignment to the JLabel
constructor.
5. A mnemonic is a key on the keyboard that you press in combination with the Alt
key to quickly access a component such as a button. When you assign a
mnemonic to a button, the user can click the button by holding down the Alt key
and pressing the mnemonic key.
6. The first occurrence of that letter appears underlined.
7. A tool tip is text that is displayed in a small box when the user holds the mouse
cursor over a component. The box usually gives a short description of what the
component does.
8. Add them to a ButtonGroup object.
9. The item is deselected, which causes the check mark to disappear. The checked
menu item component also generates an action event.
10. Dialog, DialogInput, SansSerif, Serif, and Monospaced
11. Because, as the user moves the JSlider component's knob, it will only take on
values within its established range.
12. Metal, Motif, and Windows
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 14
Multiple Choice and True/False
1. c
2. a
3. b
4. c
5. b
6. a
7. d
8. c
9. c
10. b
11. a
12. b
13. d
14. b
15. c
16. a
17. c
18. b
19. c
20. a
21. b
22. d
23. True
24. False
25. True
26. False
27. False
28. False
29. True
30. False
31. True
32. False
33. False
34. True
35. False

Find the Error


1. The tag should specify the file MyApplet.class instead of
MyApplet.java.
2. The method should call the superclass's paint method first.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

3. Call repaint instead of paint.


4. A JPanel object should override paintComponent instead of paint.
5. The class must provide all of the methods specified by the MouseListener
interface.
6. A class does not implement an adapter class, but extends it. The extends key
word should be used instead of implements.

Algorithm Workbench
1. <center><h1>My Home Page</h1></center>

2. <applet code="MyApplet.class" WIDTH=300 HEIGHT=200></applet>

3.
Line 1: Change JFrame to JApplet
Line 3: Change to public void init()
Line 5: Delete
Line 6: Delete
Line 8: Delete
Line 9: Delete
Line 15: Delete
Line 16: Delete
Line 17: Delete

4.
a) g.drawRect(50, 75, 100, 200);

b) g.fillRect(10, 90, 300, 100);

c) g.setColor(Color.blue);
g.drawOval(10, 25, 100, 50);

d) g.setColor(Color.red);
g.drawLine(0, 5, 150, 175);

e) g.setFont(new Font("Serif", Font.PLAIN, 20));


g.drawString("Greetings Earthling", 80, 99);

f) int[] xCoords = {10, 10, 50, 50};


int[] yCoords = {10, 25, 25, 10};
g.fillPolygon(xCoords, yCoords, 4);
This code will result in a square.

5.
private class MyMouseMotionListener extends MouseAdapter
{
public void mouseMoved(MouseEvent e)
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

{
mouseMovments += 1;
}
}

6. Timer tmr = new Timer(500, new MyTimerListener());

Short Answer

1. It is executed by the user's system.


2. Here are six restrictions:
• Applets cannot delete files, read the contents of files, or create files on the
user's system.
• Applets cannot run any other program on the user's system.
• Applets cannot execute operating system procedures on the user's system.
• Applets cannot retrieve information about the user's system, or the user's
identity.
• Applets cannot make network connections with any system except the
server from which the applet was transmitted.
• If an applet displays a window, it will automatically have a message such
as "Warning: Applet Window" displayed in it. This lets the user know that
the window was not displayed by an application on his or her system.
3. Applets are important because they can be used to extend the capabilities of a
Web page. Web pages are normally written in Hypertext Markup Language
(HTML). HTML is limited, however, because it merely describes the content and
layout of a Web page, and creates links to other files and Web pages. HTML does
not have sophisticated abilities such as performing math calculations and
interacting with the user. A programmer can write a Java applet to perform these
types of operations and associate it with a Web page.
4. Because the browser automatically makes the applet visible.
5. Some browsers, such as Microsoft Internet Explorer and older versions of
Netscape Navigator, do not directly support the Swing classes in applets. These
browsers require a plug-in in order to run applets that use Swing components. If
you are writing an applet for other people to run on their computers, there is no
guarantee that they will have the required plug-in. If this is the case, you should
use the AWT classes instead of the Swing classes for the components in your
applet.
6. The coordinates of the pixel in the upper-left corner are (0, 0). The coordinates of
the pixel in the upper-right corner are (599, 0). The coordinates of the pixel in the
lower-left corner are (0, 399). The coordinates of the pixel in the lower-right
corner are (599, 399). The coordinates of the pixel in the center are (299, 199).
7. When the component is first displayed and is called again any time the component
needs to be redisplayed
8. A adapter class implements one or more interfaces, and provides empty
definitions for all of the methods specified by the interfaces. When you derive a
class from one of these adapter classes, it inherits the empty methods. In your
derived class, you can override the methods you want and forget about the others.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

The API provides an adapter class for all interfaces that specify more than one
method.
9. If you want to load the sound file and keep it in memory so it can be played more
than once, or if you want to play the sound file repeatedly.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 15
Multiple Choice and True/False

1. b
2. a
3. d
4. c
5. d
6. a
7. True
8. False
9. False
10. False

Find the Error


1. The recursive method, myMethod, has no base case. So, it has no way of
stopping.

Algorithm Workbench
1.
public static void main(String [] args)
{
String str = "test string";
display(str, 0);
}

public static void display(String str, int pos)


{
if (pos < str.length())
{
System.out.print(str.charAt(pos));
display(str, pos + 1);
}
}

2.

public static void main(String [] args)


{
String str = "test string";
display(str, str.length()-1);
}
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

public static void display(String str, int pos)


{
if (pos >= 0)
{
System.out.print(str.charAt(pos));
display(str, pos - 1);
}
}
3. 10

4. 0
1
2
3
4
5
6
7
8
9
10

5. 55

6.
public static void sign(int n)
{
if (n > 0)
{
System.out.println("No Parking");
sign(n - 1);
}
}

7.
public static int factorial(int num)
{
int fac = 1;

for (int i = 1; i <=num; i++)


{
fac = fac * i;
}
return fac;
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

Short Answer
1. An iterative algorithm uses a loop to solve the problem, while a recursive
algorithm uses a method that calls itself.
2. What is a recursive algorithm's base case? What is the recursive case?
The base case is a case in which the problem can be solved without recursion. A
recursion case uses recursion to solve the problem, and always reduces the
problem to a smaller version of the original problem.
3. For question 3 the base case is reached when arg is equal to 10. For question 4
the base case is also reached when arg is equal to 10. For question 5 the base
case is reached when num is less-than or equal to 0.
4. Indirect recursion, because it involves multiple methods being called.
5. Recursive algorithms are usually less efficient than iterative algorithms. This is
because a method call requires several actions to be performed by the JVM, such
as allocating memory for parameters and local variables, and storing the address
of the program location where control returns after the method terminates.
6. By reducing the problem with each recursive call, the base case will eventually be
reached and the recursion will stop.
7. The value of an argument is usually reduced.
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 1

Starting Out with Java - From Control Structures through Objects


Answers to Review Questions

Chapter 16
Multiple Choice and True/False
1. b
2. c
3. a
4. c
5. d
6. c
7. b
8. b
9. a
10. c
11. c
12. b
13. b
14. a
15. d
16. b
17. c
18. F
19. T
20. F
21. F
22. F
23. F
24. T

Find the Error


1. The string "French Roast Dark" should be enclosed in single quotes instead of double
quotes.
2. The operator for making a not-equal-to comparison is <>.
3. The last statement should call the executeQuery method instead of the execute
method.

Algorithm Workbench
1. What SQL data types correspond with the following Java types?
• INTEGER or INT
• REAL
• CHARACTER(n) or CHAR(n) or VARCHAR(n)
• DOUBLE
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2

2. a. The table is Employee.


b. The column is Name.

3. SELECT * FROM Stock

4. SELECT TradingSymbol FROM Stock

5. SELECT TradingSymbol, NumShares FROM Stock

6. SELECT TradingSymbol FROM Stock


WHERE PurchasePrice > 25.00

7. SELECT * FROM Stock


WHERE TradingSymbol LIKE 'SU%'

8. SELECT TradingSymbol FROM Stock


WHERE SellingPrice > PurchasePrice AND
NumShares > 100

9. SELECTTradingSymbol, NumShares FROM Stock


WHERE SellingPrice > PurchasePrice AND
NumShares > 100
ORDER BY NumShares

10.
INSERT INTO Stock
(TradingSymbol, CompanyName, NumShares, PurchasePrice,
SellingPrice)
VALUES
('XYZ', 'XYZ Company', 150, 12.55, 22.47)

11.
UPDATE Stock
SET TradingSymbol = 'ABC'
WHERE TradingSymbol = 'XYZ'

12. DELETE Stock WHERE NumShares < 10

13. Connection conn = DriverManager.getConnection(DB_URL);

14. Statement stmt = conn.createStatement();

15. ResultSet result = stmt.executeQuery(sqlStatement);


Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3

16.
System.out.println(result.getString("Description"));
System.out.println(result.getString("ProdNum"));
System.out.println(result.getDouble("Price"));

17.
CREATE TABLE Cars
( Manufacturer CHAR(25),
Year INTEGER,
VehicleID CHAR(20) )

18. DROP TABLE Car

Short Answer
1. Traditional text and binary are not practical when a large amount of data must be stored
and manipulated. Many businesses keep hundreds of thousands, or even millions of data
items in files. When a text or binary file contains this much data, simple operations such
as searching, inserting, and deleting, become cumbersome and inefficient.

2. Those statements are incorrect. Apparently your fellow classmate is confusing JDBC
with SQL.

3. The data that is stored in a database is organized into one or more tables. Each table holds
a collection of related data. The data that is stored in a table is then organized into rows
and columns. A row is a complete set of information about a single item. The data that is
stored in a row is divided into columns. Each column is an individual piece of
information about the item.

4. A primary key is a column that holds a unique value for each row, and can be used to
identify specific rows.

5. A result set is an object that is somewhat similar to a collection, and contains the results
of an SQL statement.

6.
> Greater-than
< Less-than
>= Greater-than or equal-to
<= Less-than or equal-to
= Equal-to
<> Not equal-to

7. The first row is row 1. The first column is column 1.

8. The term meta data refers to data that describes other data. Result set meta data describes
the data stored in a result set. Result set meta data can be very useful if you are writing an
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 4

application that will submit an SQL query, and you don't know in advance what columns
will be returned.

9. A foreign key is a column in one table that references a primary key in another table.

You might also like