Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Chapter 1
1. a. False; b. False; c. True; d. False; e. False; f; True; g. True; h. False; i. False; j. True; k.
False; l. True.
3. Monitor and printer.
5. An operating system monitors the overall activity of the computer and provides services.
Some of these services include memory management, input/output activities, and storage
management.
7. In machine language the programs are written using the binary codes while in highlevel language the program are closer to the natural language. For execution, a highlevel language program is translated into the machine language while a machine
language need not be translated into any other language.
9. Syntax errors.
11. Instructions in a high level language are closer to the natural language, such as English, and
therefore, are easier to understand and learn than the machine language.
13. To find the weighted average of the four test scores, first you need to know each test score
and its weight. Next, you multiply each test score with its weight, and then add these numbers
to get the average. Therefore,
1. Get testScore1, weightTestScore1
2. Get testScore2, weightTestScore2
3. Get testScore3, weightTestScore3
4. Get testScore4, weightTestScore4
5.
weightedAverage = testScore1 * weightTestScore1 +
testScore2 * weightTestScore2 +
testScore3 * weightTestScore3 +
testScore4 * weightTestScore4;
15. To calculate the selling price of an item, we need to know the original price (the price the
store pays to buy) of the item. We can then the use the following formula to find the selling
price:
sellingPrice = (originalPrice + originalPrice × 0.80) × 0.90
The algorithm is as follows:
a. Get originalPrice
b. Calculate the sellingPrice using the formula:
sellingPrice = (originalPrice + originalPrice × 0.80) × 0.90
The information needed to calculate the selling price is the original price and the marked-up
percentage.
1
17. Suppose that numOfPages denotes the number of pages to be faxed and billingAmount
denotes the total charges for the pages faxed. To calculate the total charges, you need to know
the number of pages faxed.
If numOfPages is less than or equal to ten, the billing amount is service charges plus
(numOfPages × 0.20); otherwise, billing amount is service charges plus 10 × 0.20 plus
(numOfPages - 10) × 0.10.
You can now write the algorithm as follows:
a. Get numOfPages.
b. Calculate billing amount using the formula:
if (numOfPages is less than or equal to 10)
billingAmount = 3.00 + (numOfPages × 0.20);
otherwise
billingAmount = 3.00 + 10 × 0.20 + (numOfPages - 10) × 0.10;
2
Chapter 2
1.
a. False; b. False; c. False; d. False; e. True; f. True; g. True; h. False; i. True; j. False;
3.
a
5. The identifiers firstName and FirstName are not the same. Java is case sensitive. The first
character of firstName is lowercase f while the first character of FirstName is uppercase
F. So these identifiers are different.
7.
a. 3; b. 0.5; c. 4.5; d. 38.5; e. 1; f. 2;
9.
7
g. 2;
h. 420.0;
11. a and c are valid
13. a. 32 * a + b
b. '8'
c. "Julie Nelson"
d. (b * b – 4 * a * c) / (2 * a)
e. (a + b) / c * (e * f) – g * h
f.
15. x
y
z
w
t
(–b + (b * b – 4 * a * c)) / (2 * a)
=
=
=
=
=
20
15
6
11.5
4.5
17. a. x = 2, y = 5, z = 6
b. x + y = 7
c. Sum of 2 and 6 is 8
d. z / x = 3
e. 2 times 2 = 4
19. a. System.out.println(); or System.out.print("\n"); or
System.out.print('\n');
b. System.out.println("\t");
c. System.out.println("\"");
21. a. firstName
b. discountedPrice
c. numOfJuiceBottles
d. milesTravelled
e. highestTestScore
3
23. A correct answer is:
public class Exercise23
{
static final int SECRET_NUM = 11213;
static final double PAY_RATE = 18.35;
public static void main(String[] arg)
{
int one, two, three;
double first, second;
double paycheck, hoursWorked;
one = 18;
two = 11;
three = 3;
first = 25;
second = first * three;
second = 2 * SECRET_NUM;
System.out.println(first + " " + second + " " + SECRET_NUM);
hoursWorked = 35;
paycheck = hoursWorked * PAY_RATE;
System.out.println("Wages = " +
paycheck);
}
}
25. A correct answer is:
public class Exercise25
{
static final char STAR = '*';
static final int PRIME = 71;
public static void main(String[] arg)
{
int count = 1;
int sum = count + PRIME;
double x = 25.67;
int newNum = count * PRIME + 2;
sum = sum + count;
x = x + sum * count;
System.out.println(" count = " + count + ", sum = "
+ sum + ", PRIME = " + PRIME);
}
}
27. The class String is contained in the package java.lang. You do not need to import
classes from the package java.lang. The system automatically does it for you.
4
29. a. x = x + 5 – z;
b.
c.
d.
e.
f.
y =
w =
x =
sum
x =
y
w
x
=
x
* (2 * x + 5 – z);
+ 2 * z + 4;
– (z + y – t);
sum + num;
/ (y – 2);
31.
sum = a + b + (int)c;
c /= a;
b += (int)c – a;
a *= 2 * b + (int)c;
a
3
3
3
48
b
5
5
6
6
c
14.1
4.7
4.7
4.7
sum
22
22
22
22
33. (NOTE: The user input is shaded.)
Enter last name: Miller
Enter a two digit number: 34
Enter a positive integer less than 1000: 340
Name: Miller
Id: 3417
Mystery number: 3689
35. The program requires three inputs. One possible form of input is:
number
string
number
Another possible form of input is:
number string
number
5
Chapter 3
1. a. False; b. True; c. True; d. True;
3. An object is an instance of a specific class.
5.
str = new String("Java Programming");
7. The class String is contained in the package java.lang. If a program uses a class
contained in this package, the Java system automatically imports that class. Therefore,
because class String is contained in the package java.lang, it is not necessary to
explicitly import this class using the import statement.
9.
a.
b.
c.
d.
e.
11. a.
b.
Going
amusement
GOING TO THE AMUSEMENT PARK
going to the amusement park
Going *o *he amusemen* park
false
true
13. name = console.nextLine();
15. This statement causes the following input dialog box to appear that allows the user to enter
the score.
[FIG]
Chapter 3 Exercise 15
17. JOptionPane.showMessageDialog(null,
"Current Temperature: 70 degrees",
"Temperature",
19. x = console.nextInt();
ch = console.next().charAt(0);
y = console.nextInt();
21. java.io
23. acctNumber = infile.nextInt();
accountType = infile.next();
balance = infile.nextDouble();
25. a.
b.
Same as before.
The file contains the output produced by the program.
6
c.
d.
The file contains the output produced by the program. Old contents are erased.
The program would prepare the file and store the output in the file.
7
Chapter 4
1.
a. True; b. False; c. False; d. False; e. False; f. False; g. False; h. False; i. True;
3. a. true; b. false; c. true; d. true; e. true
5.
100 200 0
7.
Omit the semicolon after else.
if (score >= 60)
System.out.println("You pass.");
else
System.out.println("You fail.");
9. 3 1
11. 1 3
13. if (0 < overSpeed && overSpeed <= 5)
fine = 20.00;
else if (5 < overSpeed && overSpeed <= 10)
fine = 75.00;
else if (10 < overSpeed && overSpeed <= 15)
fine = 150.00;
else if (overSpeed > 15)
fine = 150.00 + 20.00 * (overSpeed – 15);
15. a. (i) The output is: Grade is C. The value of score after the if statement executes is 70.
(ii) The expression score = 70 in statement (ii), will result in a syntax error.
b. (i) No output. The value of score after the if statement executes is 80.
(ii) The expression score = 70 in statement (ii), will result in a syntax error.
17. a. if (x < 5)
y = 10;
else
y = 20;
b. if (fuel >= 10)
drive = 150;
else
drive = 30;
c. if (booksBought >= 3)
discount = 0.15;
else
discount = 0.0;
19. a is invalid: The expression n <= 2 evaluates to a boolean value, which is not an integral type.
The expression in the switch expression must evaluate to an integral value. b Invalid: A case
value cannot appear more than once. c, and d are valid.
21. 7
23. There is more than one answer. One possible answer is:
8
import java.util.*;
public class Errors
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int a, b;
int c;
boolean found;
System.out.print("Enter the first integer: ");
a = console.nextInt();
System.out.println();
System.out.print("Enter the second integer: ");
b = console.nextInt();
if (a > a * b && 10 < b)
found = 2 * a > b;
else
{
found = 2 * a < b;
if (found)
a = 3;
c = 15;
if (b > 0)
{
b = 0;
a = 1;
}
}
}
}
25. a. true; b. true; c. false; d. true
9
Chapter 5
1.
a. False; b. True; c. False; d. True; e. True; f. True; g. True; h. False;
3.
5
5.
When ch > 'Z'
7.
Sum = 158
9.
Sum = 158
11. 11 18 25
13. Replace the while loop statement with the following:
while (response == 'Y' || response == 'y')
Replace the output statement:
System.out.printf("%.2f + %.2f = %.2f %n",
num1, num2, (num1 - num2));
with the following:
System.out.printf("%.2f + %.2f = %.2f %n",
num1, num2, (num1 + num2));
15. 4 3 2 1
17. 0 3 8 15 24
19. Loop control variable: j
The initialization statement: j = 1;
Loop condition: j <= 10;
Update statement: j++
The statement that updates the value of s: s = s + j * (j – 1);
21. 2 7 17 37 77 157
23. a.
b.
c.
d.
e.
f.
*
infinite loop
infinite loop
****
******
***
25. The relationship between x and y is: 3y = x.
Output: x = 19683, y = 10
27.
10
0 - 24
25 - 49
50 - 74
75 - 99
100 - 124
125 - 149
150 - 174
175 – 200
29. a. Both;
b. do...while;
c. while;
d. while
31. In a pretest loop, the loop condition is evaluated before executing the body of the loop. In a posttest
loop, the loop condition is evaluated after executing the body of the loop. A posttest loop executes at
least once, while a pretest loop may not execute at all.
33. (Assume that console is a Scanner object initialized to the standard input device.)
int num;
do
{
System.out.println("Enter a number less than 20 "
+ "or greater than 75: ");
num = console.nextInt();
}
while (20 <= num && num <= 75);
35.
int i = 0, value = 0;
do
{
if (i % 2 == 0 &&
value = value
else if (i % 2 ==
value = value
else
value = value
i = i + 1;
i
+
0
+
<= 10)
i * i;
&& i > 10)
i;
- i;
}
while (i <= 20);
System.out.println("value = " + value);
The output is: value = 200
37. number = console.nextInt();
while (number != -1)
{
total = total + number;
number = console.nextInt();
}
39. a.
number = 1;
while (number <= 10)
11
{
System.out.print(number + " ");
number++;
}
System.out.println();
b.
number = 1;
do
{
System.out.print(number + " ");
number++;
}
while (number <= 10);
System.out.println();
41. 11 18 25
43 -1 0 3 8 15 24
45. 12 11 9 7 6 4 2 1
12
Chapter 6
1.
a. True; b. True; c. True; d. True; e. False; f; False; g. True; h. True; i. True; j. False ; k. False ; l.
False ;
3. JTextField.
5. To identify other GUI components such as a JTextField.
7. Through the process outlined, you have methodology which will allow you to critically think and plan
you problem solving approach. You may be able to identify the flaws involved in your thinking before
you implement it. A well-analyzed problem leads to a well designed algorithm. Also, a program that is
well-analyzed is easier to modify and spot and fix errors. No one will build a house without a
blueprint.
9.
//Program: Determine the sum and product of two numbers.
import
import
import
import
javax.swing.*;
java.lang.*;
java.awt.*;
java.awt.event.*;
public class SumProduct extends JFrame
{
private JLabel firstL, secondL, sumL, productL;
private JTextField firstTF, secondTF, sumTF, productTF;
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
public SumProduct()
{
//Create four labels
firstL = new JLabel("Enter the first number: ",
SwingConstants.RIGHT);
secondL = new JLabel("Enter the second number: ",
SwingConstants.RIGHT);
sumL = new JLabel("Sum: ", SwingConstants.RIGHT);
productL = new JLabel("Product: ",
SwingConstants.RIGHT);
//Create four textfields
firstTF = new JTextField(10);
secondTF = new JTextField(10);
sumTF = new JTextField(10);
productTF = new JTextField(10);
//Create Calculate Button
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
13
//Create Exit Button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
//Set the title of the window
setTitle("Sum and Product Calculation");
//Get the container
Container pane = getContentPane();
//Set the layout
pane.setLayout(new GridLayout(5, 2));
//Place the components in the pane
pane.add(firstL);
pane.add(firstTF);
pane.add(secondL);
pane.add(secondTF);
pane.add(sumL);
pane.add(sumTF);
pane.add(productL);
pane.add(productTF);
pane.add(calculateB);
pane.add(exitB);
//set the size of the window and display it
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double second, first, sum, product;
first = Double.parseDouble(firstTF.getText());
second = Double.parseDouble(secondTF.getText());
sum = first + second;
product = first * second;
sumTF.setText("" + sum);
productTF.setText("" + product);
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
SumProduct sumProductObject = new SumProduct();
}
}
14
11. a.
JLabel numOfCourses;
numOfCourses = new JLabel("Enter the number of courses");
b.
JButton run;
run = new JButton("Run");
c.
JTextField oneTextField ;
oneTextField = new JTextField(15);
d.
setTitle("Welcome Home!");
e.
setSize(200, 400);
f.
JTextField oneTextField;
oneTextField = new JTextField(15);
oneTextField.setText("Apple tree");
13. Lines with errors are in comments. See the corrected lines.
//The following lines added.
import javax.swing.*;
import java.awt.*;
public class RTwo extends JFrame
{
private JLabel length, width, area;
static private final int WIDTH = 400;
static private final int HEIGHT = 400;
//public RTwoProgram()
public RTwo()
{
//private JLabel length, width, area;
setTitle("Good day Area");
//length = JLabel("Enter the length);
length = new JLabel("Enter the length");
//width = JLabel("Enter the width);
width = new JLabel("Enter the width");
area = new JLabel("Area: ");
//containerPane = ContentPane();
Container pane = getContentPane();
//pane.setLayout(GridLayout(4, 1));
pane.setLayout(new GridLayout(4, 1));
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
15
public static void main( String args[] )
{
//RTwoProgram R2 = new RTwoProgram ();
RTwo R2 = new RTwo();
}
}
15. displayWelcome, getAcctNo, getPin, verifyAcct, deposit, withdraw, transfer,
tenderCash, checkAcct, and so on.
17. Customer: data members include firstName, lastName, phone, email, address; and
methods include set and get methods for data members.
Account: accountNumber, type, currentRate; method includes set and get methods for
data members.
Loan: loanNumber, type, currentRate; method includes set and get methods for data
member
Manager: data members include firstName, lastName, phone, email, address; and
methods include set and get methods for data members, createAccount, approveLoan, and
so on.
Teller: data members include firstName, lastName, phone, email, address; and methods
include set and get methods for data members, procesCheck, tenderCash, transferAmt
and so on.
19. Company: data members include accountNumber, name, phone, email, address, status,
numOpenings; and methods include set and get methods for data members, listOpenings,
requestCandidate, cancelPosition, and so on.
Candidate: data members include candidateID, firstName, lastName, phone, email,
address, wage and methods include set and get methods for data members,
listQualifications, calculateSalary, withholdIncomeTax, and so on.
Placement: data members include candidateID, companyID, openingID, startDate,
endDate; methods include set and get methods for data members, listQualifications,
calculateSalary, informCompany, informCandiadate, and so on.
Opening: data members include openingID, companyID, startDate, endDate,
qualificationID, salary; methods include set and get methods for data members.
Qualification:
data
members
include
qualificationID,
meanSalary,
maximumSalary, minimumSalary, categary; methods include set and get methods for data
members.
16
Chapter 7
1.
a. True; b. True; c. True; d. True; e. False; f. True; g. False; h. False;
3. a. 4
f. 5.00
b. 10.80
g. 2.50
c. 2.50
h. 9.00
d. 10.24
i. 28.00
e. 15.63
j. 36.00
5. a. The method main has no return type. It is a void method.
b. double
c. boolean
7. a.
b.
c.
d.
Invalid; Method type is missing.
Valid.
Invalid; Data type for the parameter b is missing.
Invalid; Missing parentheses after the method name.
9. The formal parameter x of the method signum is an integer. In the method call statement
signum(20.5), a decimal value is used which is not an integer. So we could replace the
expression signum(20.5) with the expression signum(20).
11. The method squareNum returns an int value while the expression x * x, in the return
statement is a double value. One possible solution is to replace the expression x * x with
the expression (int) x * x. Another solution is: In the method heading, change the
method type from int to double.
13. a. 4; b. 26; c. 10 4 0; d. 0
15. a. 14;
b. 15;
c. 30
17. A void method can have a return statement. If a void method has a return statement,
then it must be of the form return;, it should not return any value.
19. 12
35
14
8
10
21.
1
2
6
24
120
23.
Method headings:
public static void main(String[] args)
public static void hello(int first, double second,
char ch)
Method bodies:
main: starts at Line 4 ends at Line 13
17
hello: starts at Line 16 ends at Line 20
Method definitions:
main: starts at Line 3 ends at Line 13
hello: starts at Line 14 ends at Line 20
Formal parameters:
main: args
hello: first, second, ch
Actual parameters:
x, y, z
x + 2, y - 3.5, 'S'
Method calls: Statements in Lines 9 and 11
hello(x, y, z);
//Line 9
hello(x + 2, y - 3.5, 'S');
//Line 11
Local variables:
main: x, y, z
hello: num, y
25.
-14 20 126
15 40 407
15 80 1627
70 160 6412
27. a. Take Programming I.
b. Take Programming II.
c. Take Invalid input. You must enter a 1 or 2
d. Take Invalid input. You must enter a 1 or 2
29.
Identifier
main
local variables of main
traceMe (function name)
x (traceMe’s formal parameter)
y (traceMe’s formal parameter)
z (traceMe’s local variable)
Visibility in traceMe
Y
N
Y
Y
Y
Y
Visibility in main
Y
Y
Y
N
N
N
31. public static void func(double x, double y)
{
if (x != 0)
System.out.println(y / x);
else
System.out.println("Because the first number is 0, "
+ "we cannot divide the second "
+ "number by the first number.");
}
18
Chapter 8
1.
a. False ; b. False; c. True; d. False; e. False;
3.
Constructors have no type. Therefore the definition of the constructor with parameters should be:
public AA(int a, int b)
{
x = a;
y = b;
}
5.
a.
(i) Constructor at Line 1.
(ii) Constructor at Line 3.
(iii) Constructor at Line 4.
b.
public CC()
{
u = 0;
v = 0;
w = 0.0;
}
c.
public CC(int a)
{
u = a;
v = 0;
w = 0.0;
}
d.
public CC(int a, int b)
{
u = a;
v = b;
w = 0.0;
}
e.
public CC(int a, int b, double d)
{
u = a;
v = b;
w = d;
}
7. Automobile
9. One.
11. a. It creates the object c1, and the instance variables hr, min, and sec are initialized to 0.
19
b. It creates the object c2. The instance variable hr is initialized to 5, the instance variable
min is initialized to 12, and the instance variable sec is initialized to 30.
c. The values of the instance variables hr, min, and sec of the object c1 are set to 3, 24,
and 36, respectively.
d. The value of the instance variables hr of the object c2 is set to 9.
13. In Java, a class combines data and operations on data in a single unit. Typically, we do not
want the user to directly manipulate the data, so data members are declared as private. To
allow the users to manipulate the private members of a class, the user is provided public
members. Therefore, we need both public and private members in a class.
15. 06:23:17
06:23:17
17. In shallow copying, two or more reference variables of the same type point to the same object.
19. Both aa and bb point to the object bb.
21. The purpose of the copy constructor is to initialize an object, when the object is instantiated, using an
existing object of the same type.
23. No.
25. public class Stock
{
private
private
private
private
String name;
double previousPrice;
double closingPrice;
int numberOfShares;
Stock()
{
name = "";
previousPrice = 0.0;
closingPrice = 0.0;
numberOfShares = 0;
}
Stock(String n, int prePr, int clPr, double shares)
{
name = n;
previousPrice = prePr;
closingPrice = clPr;
numberOfShares = shares;
}
public void setName(String n)
{
name = n;
}
20
public void setPreviousPrice(double p)
{
previousPrice = p;
}
public void setClosingPrice(double c)
{
closingPrice = c;
}
public void setNumberOfShare(int ns)
{
numberOfShares = ns;
}
public String getName()
{
return name;
}
public int getPreviousPrice()
{
return previousPrice;
}
public double getClosingPrice()
{
return closingPrice;
}
public int getNumberOfShare()
{
return numberOfShares;
}
public double shareValues()
{
return numberOfShares * closingPrice;
}
public double percentGain()
{
return (previousPrice – closingPrice) / previousPrice *
}
100;
public String toString()
{
return ("Stock Name: " + name
+ "\r\n Previous Price: " + previousPrice
+ "\r\n Closing Price: " + closingPrice
+ "\r\n Number Of Shares: " + numberOfShares);
}
}
21
Chapter 9
1.
a. True; b. True; c. True; d. True; e. False; f. False; g. True;
3. a. This declaration is correct.
b. The final declaration should be: final int SIZE = 100;
c. This declaration should be: int[] numList = new int[10]
d. This declaration is correct
e. This declaration should be: double[] scores = new double[50];
5. 0 to 49
7. -3 -1 1 3 5
5 -1 8 3 -1
9. a. funcOne(list, 50);
b. System.out.print(funcSum(50, list[3]));
c. System.out.print(funcSum(list[29], list[9]));
d. funcTwo(list, Alist);
11. The elements of list are: 5, 6, 9, 19, 23, 37
13. One contains: 3 8 13 18 23
Two contains: 5 15 25 35 45 28 33 38 43 48
15. for (int i = 1; i < 9; i++)
if (scores[i] > scores[i + 1])
System.out.println(i + " and " + (i + 1)
+ " elements of scores are out of order.");
17. a. Valid
b. Invalid
c. Invalid
d. Valid
19. 0 -2
1
2
3
4
6
-12
1
13
21. a. Valid
b. Valid
c. Invalid
d. Valid
23.
int sum = 0;
int maxIndex;
int max;
for (int j = 0; j < 10; j++)
22
cars[j] = inFile.nextInt();
for (int j = 0; j < 10; j++)
sum = sum + cars[j];
System.out.println("The total number of cars sold = " + sum);
max = cars[0];
for (int j = 1; j < 10; j++)
if (max < cars[j])
max = cars[j];
System.out.println("The salesperson(s) selling the maximum "
+ "number of cars: ");
for (int j = 0; j < 10; j++)
if (max == cars[j])
System.out.print(j + ", ");
System.out.println();
25. One contains: 3 8 13 18 23
Two contains: 5 15 25 35 45 28 33 38 43 48
27. The base address of the array.
29.
a.
b.
c.
d.
e.
30
5
6
row
column
31. a. beta is initialized to zero.
b.
First row of beta:
0 1 2
Second row of beta: 1 2 3
Third row of beta: 2 3 4
c.
First row of beta:
0 0 0
Second row of beta: 0 1 2
Third row of beta: 0 2 4
d.
First row of beta:
0 2 0
Second row of beta: 2 0 2
Third row of beta: 0 2 0
33.
int[][] temp = {{6, 8, 12, 9},
{17, 5, 10, 6},
{14, 13, 16, 20}};
35. a.
public static void print(int[][] x, int rowSize, int columnSize)
{
for (int i = 0; i < rowSize; i++)
{
for (int j = 0; i < columnSize; j++)
23
System.out.print(x[i][j] + " ");
System.out.println();
}
}
b.
37.
print(times, 30, 7);
print(speed, 15, 7);
print(trees, 100, 7);
print(students, 50, 7);
list = ["One", "Six", "Two", "Three", "Four", "Five"];
39.
strList:
intList:
strList:
intList:
[Hello, Happy, Sunny]
[10, 20, 30]
[Hello, Happy, Joy, Sunny]
[10, 30]
24
Chapter 10
1.
a. False; b. False; c. False; d. True
3.
Some of the data members that can be added to the class Employee are: department, salary,
employeeCategory (such as supervisor and president), and employeeID. Some of the methods
are: setInfo, getSalary, getEmployeeCategory, setSalary.
5.
Person
Employee
Student
Instructor
7. The class Animal is the base class and the class Dog is the derived class.
9.
a.
The statement
class BClass AClass
should be
class BClass extends AClass
b. Variables u and v are private in class AClass and cannot be accessed directly in class
BClass.
11.
a.
public YClass()
{
a = 0;
b = 0;
}
b.
public XClass()
{
super(0, 0);
z = 0;
}
c.
public void two(int x, int y)
{
a = x;
b = y;
}
13. In overloading a method, two or more methods have the same name but have different formal
parameter list. In overriding, you are redefining a method of a superclass in a subclass. The
two methods (the method in the superclass and its redefinition in the subclass) have the same
name and formal parameter list.
25
15. The class GradStudent has two printGrades
public void printGrades()
methods and their headings are:
and
public void printGrades(String status)
17.
a.
public void setData(int a, int b, int c)
{
super.setData(a, b);
z = c;
}
b.
public void print()
{
super.print();
System.out.println(z);
}
19.
The public members of a class can be accessed anywhere the class is used. The
protected members of the base class can be directly accessed only by the methods
of the derived class.
statements are legal because a reference variable of a superclass type can point
to an object of a subclass. Therefore, the formal parameter st can point to the objects
student1 and student2.
21. These
23. An abstract method is a method that only has the heading with no body. Moreover, the heading of an
abstract method contains the reserved word abstract and ends with a semicolon.
25. Java does not support multiple inheritance. That is, a class can extend only the definition of one class.
In other words, a class can be derived from only one existing class. However, a Java program might
contain a variety of GUI components and thus generates a variety of events such as window events,
mouse events, as well as action events. These events are handled by separate interfaces. Therefore, a
program might need to use more than one interface.
26
Chapter 11
1. a. True; b. False; c. False; d. True; e. False; f. True; g. True; h. False; i. True; j. False.
3. The program will terminate with an error message.
5. If an exception is thrown in a try block, the remaining statements in that try block are ignored.
The program searches the catch blocks in the order they appear after the try block, and looks
for an appropriate exception handler. If the type of thrown exception matches the parameter type
in one of the catch blocks, the code of that catch block executes and the remaining catch
blocks after this catch block are ignored. If there is a finally block after the last catch block,
the finally block executes regardless of whether an exception occurs.
7. a. Leaving try block.
b. Balance must be greater than 1000.00.
c. Balance must be greater than 1000.00.
9. a.
Entering the try block.
Exception: Lower limit violation.
After the catch block
b.
Entering the try block.
Exception: / by zero
After the catch block
c.
Entering the try block.
Exiting the try block.
After the catch block
d.
Entering the try block.
Exception: / by zero
After the catch block
11. Typically constructors are the only methods that you include when you define your own exception
class.
27
13. There are two corrections in this program. The corrected program is as follows : (The lines in
green indicate the corrections.)
import java.io.*;
import java.util.*;
public class SAverage
{
public static void main(String[] args)
{
double test1, test2, test3, test4;
double average;
try
{
Scanner inFile = new
Scanner(new FileReader("test.txt"));
PrintWriter outFile = new
PrintWriter("testavg.out");
test1
test2
test3
test4
=
=
=
=
inFile.nextDouble();
inFile.nextDouble();
inFile.nextDouble();
inFile.nextDouble();
outFile.printf("Test scores: %.2f %.2f %.2f %.2f %n",
test1, test2, test3, test4);
average = (test1 + test2 + test3 + test4) / 4.0;
//outFile.println("Average test score: %.2f",
//
average);
//Replace these lines with the following
outFile.printf("Average test score: %.2f%n",
average);
outFile.close();
}
//Change the order of the following two catch
//blocks as follows
catch (FileNotFoundException e)
{
System.out.println(e.toString());
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
}
15.
public class Test
{
public static void main(String[] args)
{
int i = 8;
28
try
{
if (i < 5)
throw new TornadoException();
else
throw new TornadoException(i);
}
catch (TornadoException e)
{
System.out.println(e.getMessage());
}
}
}
17. A method specifies the exceptions it throws in its heading using the throws clause.
19. Any class can implement an interface. The three different options are to use an inner class, or an
anonymous inner class or the application (the applet) program class itself to implement an
interface.
29
Chapter 12
1.
a. True; b. True; c. True; d. False; e. False; f. False; g. True; h. False; i. False.
3.
JTextField and JTextArea.
5.
Sometimes you want the user to select from a set of predefined values. In addition to freeing the user
from typing in such values, to get a precise input you want the user to select a value from a set of given
values.
7.
a.
private String[] fruitNames = {"orange",
"apple",
"banana",
"grape",
"pineapple"};
private JList fruitJList;
private JScrollPane selectionJS;
pictureJList = new JList(fruitNames);
fruitJList.setVisibleRowCount(3);
fruitJList.setSelectionMode
(ListSelectionModel.SINGLE_SELECTION);
fruitJList.addListSelectionListener(this);
selectionJS = new JScrollPane(fruitJList);
b.
JCheckBox qualityCB;
qualityCB = new JCheckBox("draft");
c.
private JRadioButton homeRB, visitorRB, neutralRB;
private ButtonGroup ColorSelectBGroup;
homeRB = new JRadioButton("Home");
visitorRB = new JRadioButton("Visitor");
neutralRB = new JRadioButton("Neutral");
ColorSelectBGroup = new ButtonGroup();
ColorSelectBGroup.add(homeRB);
ColorSelectBGroup.add(visitorRB);
ColorSelectBGroup.add(neutralRB);
d.
private JMenuBar menuMB = new JMenuBar();
e.
private Font myFont = new Font("Courier", Font.BOLD, 32);
f.
private Color myColor = new Color(255, 200, 64);
30
Chapter 13
1.
a. True; b. True; c. False; d. False; e. False
3.
The case in which the solution is defined in terms of smaller versions of itself.
5.
A method that calls another method and eventually results in the original method call is said to be
indirectly recursive.
7.
a. The statements in Lines 2 and 3.
b. The statement in Lines 4 and 5.
c. Any nonnegative integer.
d. It is a valid call. The value of mystery(0) is 0.
e. It is a valid call. The value of mystery(5) is 15.
f. It is an invalid call. It will result in the infinite recursion.
9.
a. It does not produce any output.
b. 5 6 7 8 9
c. . It does not produce any output.
d. It does not produce any output.
11. a. Go Go Go Go Go Go Stop!
b. Go Go Stop!
c. Infinite loop, continuously printing Go.
13. a. 2
b. 3
c. 5
d. 21
15.
if n 0
0
multiply (m, n) m
if n 1
m multiply (m, n 1) otherwise
31
Chapter 14
1.
a. False; b. True; c. False; d. False; e. False; f True
3. a.
public static int seqOrderedSearch(int[] list, int listLength,
int searchItem)
{
int loc;
boolean found = false;
for (loc = 0; loc < listLength; loc++)
if (list[loc] >= searchItem)
{
found = true;
break;
}
if (found)
if (list[loc] == searchItem)
return loc;
else
return -1;
else
return -1;
}
b. i. 5
ii. 7
iii. 8
iv. 11
5.
List before the first iteration: 26, 45, 17, 65, 33, 55, 12, 18
List after the first iteration: 12, 45, 17, 65, 33, 55, 26, 18
List after the second iteration: 12, 17, 45, 65, 33, 55, 26, 18
List after the third iteration: 12, 17, 18, 65, 33, 55, 26, 45
List after the fourth iteration: 12, 17, 18, 26, 33, 55, 65, 45
List after the fifth iteration: 12, 17, 18, 26, 33, 55, 65, 45
List after the sixth iteration: 12, 17, 18, 26, 33, 45, 65, 55
List after the seventh iteration: 12, 17, 18, 26, 33, 45, 55, 65
7.
3
9.
10, 12, 18, 21, 25, 28, 30, 71, 32, 58, 15
11. Selection sort: 49,995,000 comparisons; insertion sort: 25,007,499 comparisons
13.
public static void descendingToAscending(int[] list, int length)
{
int temp;
int index;
int last = length - 1;
32
for (index = 0; index <= (length - 1) / 2; index++)
{
temp = list[index];
list[index] = list[last];
list[last] = temp;
last--;
}
}
33