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.


Correct Option: C
Explanation:

To solve this question, the user needs to understand the concepts of sorting arrays and the differences between the Object and Integer classes.

The code creates an array of Objects that includes Integer, String, and Boolean objects, then sorts the array using the Arrays.sort() method. Finally, the code prints out each object in the sorted array using a for loop.

Now, let's go through each option and explain why it is right or wrong:

A. Compilation fails due to an error in line 23. This option is incorrect because there are no errors in the syntax of line 23. The code creates an array of objects and initializes it with Integer, String, and Boolean objects.

B. Compilation fails due to an error in line 29. This option is incorrect because there are no errors in the syntax of line 29. The Arrays.sort() method is a valid method and can be used to sort arrays.

C. A ClassCastException occurs in line 29. This option is correct. The code attempts to sort an array of Objects, which includes Integer, String, and Boolean objects. When the sort method attempts to compare the elements in the array, a ClassCastException occurs because the elements are not all of the same type. The Integer objects are not comparable to the String and Boolean objects, resulting in an exception.

D. A ClassCastException occurs in line 31. This option is incorrect. The for loop uses the toString() method to print out each object in the array, which is a valid method for all objects. However, the exception occurs during the sort method in line 29, not during the printing of the objects.

The Answer is: C

Find more quizzes: