Exam Prep Practice Questions

Question 1 A method to compute the sum of all elements in an array of int is needed. The following proposed method is incomplete:
1. public int total( int[] x ){
2.   int i, t = 0 ;
3.   -select statement to go here
4.   { t += x[ i++ ] ;
5.   }
6.   return t ;
7. }

What is the correct statement for line 3?

  • A. for( int i = 0 ; i < x.length ; )

  • B. for( i = 0 ; i < x.length ; )

  • C. for( i = 0 ; i < x.length ; i++ )

  • D. for( i = 1 ; i <= x.length ; i++ )

A1: Answer B is correct. It avoids the errors of the other options. Answer A results in a compiler error because i is already declared in line 2. Therefore, answer A is incorrect. Answer C is incorrect because the loop counter i is incremented twice, thus skipping alternating array ...

Get Java 2™ Programmer Exam Cram™ 2 (Exam CX-310-035) now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.