Chapter 8 - Debugging Flashcards
- You coded the following on line 26 of the class Test.java:
int a[6] = { 2, 7, 8, 9, 11, 16 }; // line 26
When you compile, you get the following messages:
Test.java:26: error: ‘]’ expected int a[6] = { 2, 7, 8, 9, 11, 16}; // line 26
^
Test.java:26: error: not a statement int a[6] = { 2, 7, 8, 9, 11, 16}; // line 26
^
Test.java:26: error: ‘;’ expected int a[6] = { 2, 7, 8, 9, 11, 16}; // line 26
^
3 errors
Explain what the problem is and how to fix it.
When declaring an array, the square brackets should be empty. Replace a[6] by a[]:
int a[] = { 2, 7, 8, 9, 11, 16}; // line 26
- You coded the following on lines 26, 27, and 28 of the class Test.java:
int [] a = { 2, 7, 8, 9, 11, 16 }; // line 26 of class Test.java for ( int i = 0; i \<= a.length; i++ ) // line 27 of class Test.java System.out.println( a[i] ); // line 28 of class Test.java
The code compiles properly, but when you run, you get the following output:
2
7
8
9
11
16
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 6 at Test.main(Test46.java:28)
Explain what the problem is and how to fix it.
Index a.length is out of bounds; when i is equal to a.length, the expression a[i] will generate a run-time exception. Replace <= with < in the loop condition:
for ( int i = 0; i < a.length; i++ ) // line 27 of class Test.java
- You coded the following in the class Test.java:
int [] a = { 1, 2, 3 };
int [] b = { 1, 2, 3 };
if ( a == b )
System.out.println( “Arrays are equal” );
else
System.out.println( “Arrays are NOT equal” );
The code compiles properly and runs, but the result is not what you expected; the output is
Arrays are NOT equal
Explain what the problem is and how to fix it.
We cannot compare two arrays using aggregate comparison. Aggregate comparison compares the respective memory locations of the two arrays, which are different. We need to compare the elements one at a time.
- You coded the following in the class Test.java:
int [] a = { 1, 2, 3 };
System.out.println( a );
The code compiles properly and runs, but the result is not what you expected; instead of 1 2 3, the output is similar to the following:
[I@f0326267
Explain what the problem is and how to fix it.
The output statement prints the hash code of the array, which consists of the array symbol [, an I to indicate that the elements are integers, an @ sign, and the memory location of the array a. If we want to output the elements of the array, we need to loop through the array elements and output them one at a time