Given: 23. Object [] myObjects = { 24. new Integer(12), 25. new String("foo"), 26. new Integer(5), 27. new Boolean(true) 28. }; 29. Arrays.sort(myObjects); 30. for(int i=0; i

  1. Compilation fails due to an error in line 23.

  2. Compilation fails due to an error in line 29.

  3. A ClassCastException occurs in line 29.

  4. A ClassCastException occurs in line 31.

  5. The value of all four objects prints in natural order.


Correct Option: C

AI Explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) Compilation fails due to an error in line 23 - This option is incorrect because there is no error in line 23. The array myObjects is properly declared and initialized.

Option B) Compilation fails due to an error in line 29 - This option is incorrect because there is no error in line 29. The Arrays.sort() method is called to sort the array myObjects. Although the array contains objects of different types, the Arrays.sort() method can still be applied.

Option C) A ClassCastException occurs in line 29 - This option is correct. The Arrays.sort() method attempts to sort the array myObjects, which contains objects of different types. However, sorting requires the objects to be comparable with each other, and the Arrays.sort() method cannot compare objects of different types. This results in a ClassCastException at runtime.

Option D) A ClassCastException occurs in line 31 - This option is incorrect. The ClassCastException occurs in line 29, not line 31. Line 31 is responsible for printing the elements of the array, not for sorting or casting.

Option E) The value of all four objects prints in natural order - This option is incorrect. Since a ClassCastException occurs in line 29, the Arrays.sort() method fails to sort the array, and the printing of the array elements in line 31 will not result in the desired natural order.

The correct answer is C. A ClassCastException occurs in line 29. This option is correct because the Arrays.sort() method cannot compare objects of different types, resulting in a ClassCastException at runtime.

Find more quizzes: