Chapter 8 - Identifying Errors in Code Flashcards

1
Q
  1. Where is the error in this code sequence?

double [ ] a = { 3.3, 26.0, 48.4 };
a[4] = 2.5;

A

Index 4 is out of bounds; the statement a[4] = 2.5; will generate an
ArrayIndexOutOfBoundsException at run time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. Where is the error in this code sequence?

double [ ] a = { 3.3, 26.0, 48.4 };
System.out.println( a[-1] );

A

Index -1 is out of bounds; the statement System.out.println( a[-1] ); will
generate an ArrayIndexOutOfBoundsException at run time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. 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] );

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Where is the error in this code sequence?

double a[3] = { 3.3, 26.0, 48.4 };

A

When declaring an array, the square brackets should be empty. Replace a[3] with
a[ ]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. 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” );

A

We cannot compare two arrays using aggregate comparison. We need to compare the elements one at a time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
  1. Where is the error in this code sequence?

int [ ] a = { 3, 26, 48, 5 };
a.length = 10;

A

We cannot assign a value to the final variable length.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
  1. Where is the logic error in this code sequence?

int [ ] a = { 3, 26, 48, 5 };
System.out.println( “The array elements are “ + a );

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
  1. 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 };
A

We cannot initialize an Integer array with a Double and a String element; array
elements must be of type Integer (or type int).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
  1. Where is the error in this code sequence?

double [ ] a = { 3.3, 26.0, 48.4 };
System.out.println( a{1} );

A
Square brackets ( [] ) need to be used when accessing an array element, not curly
braces ( { } ). It should be a[1], not a{1}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly