Answers To Review Questions: Starting Out With Java - From Control Structures Through Objects
Answers To Review Questions: Starting Out With Java - From Control Structures Through Objects
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
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. 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
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
• 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);
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
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
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
Algorithm Workbench
1. if (y == 0)
x = 100;
2. if (y == 10)
x = 0;
else
x = 1;
4. if (minimum)
hours = 10;
9. if (title1.compareTo(title2) < 0)
System.out.println(title1 + " " + title2);
else
System.out.println(title2 + " " + title1);
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
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
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
Algorithm Workbench
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');
5. double total = 0;
for (int num = 1, denom = 30; num <= 30; num++, denom--)
total += num / denom;
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 static void main(String[] args)
{
Random rand = new Random();
System.out.println(rand.nextInt(10) + 1);
}
}
16.
import java.util.Random;
}
}
17.
PrintWriter outFile =
new PrintWriter("NumberList.txt");
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
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
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
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
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
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
Algorithm Workbench
1.
a) UML diagram:
b) Class code:
/**
setName method
@param n The pet's name.
*/
/**
setAnimal method
@param a The type of animal.
*/
/**
setAge method
@param a The pet's age.
*/
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3
/**
getName method
@return The pet's name.
*/
/**
getAnimal method
@return The type of animal.
*/
/**
getAge method
@return The pet's age.
*/
2.
a) Constructor:
c) UML diagram:
3.
a)
public Square()
{
sideLength = 0.0;
}
b)
public Square(double s)
{
sideLength = s;
}
Short Answer
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
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
Algorithm Workbench
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]);
}
8. a) numberArray[0][0] = 145;
b) numberArray[8][10] = 18;
10.
a) Sum each row in the array:
// 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
Short Answer
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
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.
if (c.getRadius() == radius)
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 2
status = true;
else
status = false;
return status;
}
return status;
}
2.
a) 3
b) 3
c) 1
d) 0
e) Thing.putThing(5);
Short Answer
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
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
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++;
}
if (str2.endsWith(".com"))
Gaddis: Starting Out with Java: From Control Structures through Objects, 5/e 3
status = true;
else
status = false;
return status;
}
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
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
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
4. super(x, y, z);
5. setValue(10);
Or
super.setValue(10);
6.
public int getValue()
{
return value;
}
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
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
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
if (element == -1)
throw new Exception("Element not found.");
else
return element;
}
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
6.
throw new NegativeNumber();
Or
throw new NegativeNumber(number);
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");
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
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
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));
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
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
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.
5.
selectionIndex = myComboBox.getSelectedIndex();
10.
JTextArea textInput = JTextArea(10, 15);
JScrollPane scrollPane = new JScrollPane(textInput);
textInput.setLineWrap(true);
textInput.setWrapStyleWord(true);
11.
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
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
Algorithm Workbench
1. <center><h1>My Home Page</h1></center>
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);
c) g.setColor(Color.blue);
g.drawOval(10, 25, 100, 50);
d) g.setColor(Color.red);
g.drawLine(0, 5, 150, 175);
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;
}
}
Short Answer
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
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
Algorithm Workbench
1.
public static void main(String [] args)
{
String str = "test string";
display(str, 0);
}
2.
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;
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
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
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
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'
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) )
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
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.