Chapter 2

Section 2.1

public static void main(args[]) { // type missing

int x = 3.45; //This is not an integer

float w = x / 2;

char ch = 'a' + 'b';

if (x = y) { //this is an assignment, not a Boolean

//also, y never declared

int z = x++; //scope of z inside if statement

else

int z = y++; //scope of z inside else statement

}

System.out.println(z + “***” + sqrt(z));

//z not in this scope. Also, sqrt should be Math.sqrt().

}

Better answer would be:

public static void main(String[] args)

{

int x = 3;

int y = 2;

int z;

float w = x / 2;

char ch = 'a' + 'b';

if (x == y) {

z = x++;

} else {

z = y++;

}

System.out.println(z + "***" + Math.sqrt(z));

}

2.

Identify any of the following statements that would throw an exception. Identify the kind of exception.

int [] x = new int [10 ];

x [x.length] = 5; //ArrayIndexOutOfBoundsException: Last array element is x[9], not x[10]

x [x.length -1] = -95;

x [0] = 7;

int n = 0;

x [n] = x.length /n; //ArithmeticException: Integer division by zero

String num = "334.e5";

n = Integer.parseInt(num); //NumberFormatException: num is not an integer

double y = Double.parseDouble(num);

Section 2.2

  1. A checked exception is an error that is normally not due to programmer error and is beyond the control of the programmer. Unchecked exceptions are error conditions that may occur as a result of programmer error or as a result of serious external conditions that are considered unrecoverable. Example of checked: IOException (FileNotFoundException) caused by programmer attempting to access a non-existent file. Example of unchecked: ArrayIndexOutOfBoundsException due to programmer error. Exception classes that are subclasses of Error of RunTimeException are unchecked, all others are checked.

2.

The unchecked exceptions in the class Exception are programming errors and can be prevented with defensive programming; the unchecked exceptions in class Error are due to serious external conditions (e.g. out of memory).

3. ArithmeticException, IllegalArgumentException, NumberFormatException,

IndexOutOfBoundsException

4.

EOFException and FileNotFoundException.

Section 2.3

1. Exception in thread "main" java.lang.NumberFormatException

at Integer.parseInt(Integer.java:430)

at Others.second(Others.java:20)

at Others.first(Others.java:10)

at MyApp.main(MyApp.java:10)

2.

try {

...

} catch (NumberFormatException ex){

...

} catch (RuntimeException ex){

...

} catch (Exception ex){

...

}

Section 2.4

  1. The throws clause denotes that a method may throw a particular type of checked expression. The throw statement is used to throw an exception when an error condition is detected.

2.

It is useful to declare and exception rather than catching it in a method when a higher-level module already contains a catch clause for this exception type.

3. When the exception is unchecked and is likely to be caught and corrected in a higher-level method.

4.

Checked exceptions should appear in a throws clause. Including unchecked exceptions in a throws clause is legal, but it is considered a poor programming practice and should be avoided.

  1. a. Use a @throws tag and a throws clause to declare that the checked exception is thrown:

throws IOException

b. throw an illegal argument exception in the lower level method. Assuming num is the parameter:

if (num < 0)

throw new IllegalArgumentException(num

+ " is not positive");

c. Catch the exception in the lower level method.

catch (IOException ex)

d. Use a @throws tag to indicate that the unchecked exception may be thrown

@throws NumberFormatException

e. Use a @throws tag to indicate that the unchecked exception may be thrown and execute the statement

throw new NameOfException

when the condition is detected.

Section 2.5

  1. Using a team to hand-trace the program or algorithm has been shown to be a effective way of removing defects and detecting errors. The designer may know the purpose of each step, but the process of explaining it to and hand-tracing with a team will catch more errors and defects.

2.

minN == maxN (e.g. minN = maxN = 1), and test for input 1 and 2

minN > maxN (e.g. minN = 5 and maxN = 2);

3. We test each path through the method as it is implemented during white box testing, but we don't check whether the method implementation matches its specification in the interface. This is the done by black-box testing.

4.

White-box testing data

Statement coverage tests:

Prompt / minN / maxN / n / Expected Result
“My prompt” / 5 / 1 / - / Should throw an IllegalArgumentException
“My prompt” / 1 / 5 / 3.5 / "Bad numeric string -- Try again"
“My prompt” / 1 / 5 / 2 / Should work fine
“My prompt” / 5 / 1 / -2 / Out of bounds, should ask for another number

Branch coverage tests:

Prompt / minN / maxN / n / Expected Result
“My prompt” / 1 / 5 / 3 / Should work fine
“My prompt” / 5 / 1 / - / Should throw an IllegalArgumentException
“My prompt” / 1 / 5 / -1 / Should ask for another number

Path coverage tests:

Prompt / minN / maxN / n / Expected Result
“My prompt” / 5 / 1 / - / Should throw an IllegalArgumentException
“My prompt” / 1 / 5 / 6 / Should ask for another number
“My prompt” / 1 / 5 / -1 / Should ask for another number
“My prompt” / 1 / 5 / 3 / Should work fine
“My prompt” / 1 / 5 / 3.5 / "Bad numeric string -- Try again"

Black-box testing data

Prompt / minN / maxN / n / Expected Result
NULL / 1 / 5 / 3 / Should work fine
“” / 1 / 5 / 3 / Should work fine
“My prompt” / 0 / 0 / 0 / Boundary case, should work fine
“My prompt” / 5 / 1 / - / Boundary case, should throw an IllegalArgumentException
“My prompt” / -10 / 5 / 0 / Should work even with negative values
“My prompt” / -10 / -5 / -8 / Should work even with negative values
“My prompt” / 0 / 5 / 0 / Should work fine
“My prompt” / 0 / 5 / 5 / Should work fine
“My prompt” / 0 / 5 / -1 / Should not accept n (out of range)
“My prompt” / 0 / 5 / 6 / Should not accept n (out of range)
“My prompt” / 0 / 5 / 3.5 / Should not accept a double value (must be integer)

5. a. white-box testing

b. integration testing

c. integration testing

d. integration testing

e. white-box testing

Section 2.6

  1. Diagnostic output statements could be placed within the loop before the if statement to prove that the condition being checked is what we expect:

System.out.println("x[" + i + "] = " + x[i]

+ ", current max = " + maxSoFar);

A statement could then be added in the if statement after the assignment (make sure you insert braces) to let us know that a new maximum value was found.

System.out.println("New max value found: " + maxSoFar);

Finally you could add a statement to display maxSoFar just prior to the return.

2.

Step Into goes inside the methods when stepping through statements. Step Over executes methods as a whole, and does not step through the statements within the method in the current statement. In simple words, when stepping through statements, “Step Into” steps into the methods and “Step Over” steps over the methods.

3. The breakpoint at the while loop allows us to check all conditions and

variables at each loop iteration, helping us narrow down looping problems.

The breakpoint at the return statement allows us to check all

variables just prior to returning from the method.

4.

After selecting Continue after the program stops in the first breakpoint (just before the loop), the next stop would be at the second breakpoint (just after the loop). Note that it would not stop after every loop iteration, but just before the first iteration and after the last iteration.

Section 2.7

1. //invariant: Each prior value of inRange was false

//assert: minN <= n <= maxN

Section 2.8

1. a. n2 , O(n2)

b. 2n, O(n)

c. n x (n-1), O(n2)

d. println never executes (i is always larger than j), but the if statement executes 1 + 2 + 3 + … (n-1) times, so loop is O(n2)

2.

To solve this we need to find a point where

cn3 = n3 – 5n2 + 20n – 10

If we let n be n0 and solve for c, we get

c = 1 – 5/n0 + 20/n02 – 10/n03

For an n0 of 1, this gives us a c of 6. So 6n3n3 – 5n2 + 20n – 10 for all n greater than 6 as shown in the figure.

3. logarithms are base 2.

O(f(n)) / f(2000) / f(4000) / f(4000)/f(2000)
O(log n) / 10.97 / 11.97 / 1.09
O(n) / 2000 / 4000 / 2
O(n log n) / 21931.6 / 47863.1 / 2.18
O(n2) / 4000000 / 16000000 / 4
O(n3) / 8000000000 / 64000000000 / 8
O(f(n)) / f(4000) / f(8000) / F(8000)/f(4000)
O(log n) / 11.97 / 3.9 / 1.08
O(n) / 4000 / 8000 / 2
O(n log n) / 47863.1 / 103726.3 / 2.17
O(n2) / 16000000 / 64000000 / 4
O(n3) / 64000000000 / 512000000000 / 8

4.

Approximate performance time for (from the plot in figure 2.14)

Function / n = 20 / n = 40
Logarithmic / 1800 / 2050
Linear / 2000 / 4000
Log-linear / 2200 / 5300
Quadratic / 2000 / 8000
Cubic / 4000 / Out of range
Exponential / Out of range / Out of range

Is this the intended effect or is the book missing the real functions?