Java OCA OCP Practice Question 352

Question

Assuming we have a valid, non-null LetterManager object whose value is initialized by the blank line shown here,

which of the following are possible outputs of this application?

Choose all that apply

1: class Letter {} 
2: interface LetterManager { public java.util.List<Letter> getLetters(); } 
3: public class Main { 
4:   public static void main(String[] args) { 
5:     LetterManager house = ______________ 
6:     Letter letter = house.getLetters().get(0); 
7:     for(int i=0; i<house.getLetters().size();  
8:       letter = house.getLetters().get(i++)) { 
9:       System.out.println("Cluck"); 
10: } /*  w w  w  .  j  ava 2s  . c o  m*/
11:} 
12:} 
  • A. The code will not compile because of line 6.
  • B. The code will not compile because of lines 7-8.
  • C. The application will compile but not produce any output.
  • D. The application will output Cluck exactly once.
  • E. The application will output Cluck more than once.
  • F. The application will compile but produce an exception at runtime.


D, E, F.

Note

The code compiles without issue, so options A and B are incorrect.

If house .getLetters() returns an array of one element, the code will output Cluck once, so option D is correct.

If house.getLetters() returns an array of multiple elements, the code will output Cluck once for each element in the array, so option E is correct.

Alternatively, if house.getLetters() returns an array of zero elements, then the code will throw an IndexOutOfBoundsException on the call to house.getLetters().get(0);

option C is not possible and option F is correct.

The code will also throw an exception if the array returned by house.getLetters() is null, so option F is possible under multiple circumstances.




PreviousNext

Related