Chapter 8 - Identifying Errors in Code Flashcards
- Where is the error in this code sequence?
double [ ] a = { 3.3, 26.0, 48.4 };
a[4] = 2.5;
Index 4 is out of bounds; the statement a[4] = 2.5; will generate an
ArrayIndexOutOfBoundsException at run time.
- Where is the error in this code sequence?
double [ ] a = { 3.3, 26.0, 48.4 };
System.out.println( a[-1] );
Index -1 is out of bounds; the statement System.out.println( a[-1] ); will
generate an ArrayIndexOutOfBoundsException at run time.
- Where is the error in this code sequence?
double [ ] a = { 3.3, 26.0, 48.4 };
for ( int i = 0; i <= a.length; i++ )
System.out.println( a[i] );
Index a.length is out of bounds; when i is equal to a.length, the expression
a[i] will generate an ArrayIndexOutOfBoundsException at run time.
Replace <= with < in the loop condition
- Where is the error in this code sequence?
double a[3] = { 3.3, 26.0, 48.4 };
When declaring an array, the square brackets should be empty. Replace a[3] with
a[ ]
- Where is the error (although this code will compile and run) in this code sequence?
int a[ ] = { 3, 26, 48, 5 };
int b[ ] = { 3, 26, 48, 5 };
if ( a != b )
System.out.println( “Array elements are NOT identical” );
We cannot compare two arrays using aggregate comparison. We need to compare the elements one at a time.
- Where is the error in this code sequence?
int [ ] a = { 3, 26, 48, 5 };
a.length = 10;
We cannot assign a value to the final variable length.
- Where is the logic error in this code sequence?
int [ ] a = { 3, 26, 48, 5 };
System.out.println( “The array elements are “ + a );
Although the code compiles, it outputs the hash code of the array a. To
output the elements of the array, we need to loop through the array elements and
output them one by one.
- Where is the error in this code sequence?
Integer i1 = 10; Integer i2 = 15; Double d1 = 3.4; String s = new String( "Hello" ); Integer [ ] a = { i1, i2, d1, s };
We cannot initialize an Integer array with a Double and a String element; array
elements must be of type Integer (or type int).
- Where is the error in this code sequence?
double [ ] a = { 3.3, 26.0, 48.4 };
System.out.println( a{1} );
Square brackets ( [] ) need to be used when accessing an array element, not curly braces ( { } ). It should be a[1], not a{1}