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:}
D, E, F.
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.