NumZero

<source lang="java"> class numZero { /** * If arr is null throw NullPointerException, else return the * number of occurrences of zero in arr */ public static int numZero (int[] arr) { int count = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] == 0) { count++; } } return count; }

/** * Driver method for numZero. */ public static void main(String[] argv) { // Read an array from standard input, call numZero() int[] inArr = new int[argv.length]; if (argv.length == 0) { System.out.println("Usage: java numZero v1 [v2] [v3] ... "); return; }

for (int i = 1; i< argv.length; i++) { try { inArr[i] = Integer.parseInt(argv[i]); } catch (NumberFormatException e) { System.out.println ("Entry must be a integer, using 1."); inArr[i] = 1; } }

System.out.println("Number of zeros is: " + numZero(inArr)); } } </source>

The fault in this program is that it starts looking for zeroes at index 1 instead of index 0, as is necessary for arrays in Java. For example, numZero([2, 7, 0]) correctly evaluates to 1, while numZero([0, 7, 2]) incorrectly evaluates to 0. In both of these cases the fault is executed. Although both of these cases result in an error, only the second case results in failure. To understand the error states, we need to identify the state for the program. The state for numZero consists of values for the variables x, count, i, and the program counter (denoted PC). For the first example given above, the state at the if statement on the very first iteration of the loop is (x = [2, 7, 0], count = 0, i = 1, PC = if). Notice that this state is in error precisely because the value of i should be zero on the first iteration. However, since the value of count is coincidentally correct, the error state does not propagate to the output, and hence the software does not fail. In other words, a state is in error simply if it is not the expected state, even if all of the values in the state, considered in isolation, are acceptable. More generally, if the required sequence of states is s0 , s1 , s2 , ..., and the actual sequence of states is s0 , s2 , s3 , ..., then state s2 is in error in the second sequence.

In the second case the corresponding error state is (x = [0, 7, 2], count = 0, i = 1, PC = if). In this case, the error propagates to the variable count and is present in the return value of the method. Hence a failure results.


Regarding the numZero method, some test cases that could be designed for this code are:

  • ([2, 7, 0], 1)
  • ([0, 7, 2], 1)
  • ([], 0)
  • ([0, 0, 0], 3)