Java SE 8 Programmer II: Exam 1Z0-809 | Question Solution

Java SE 8 Programmer II: Exam 1Z0-809 Question Solution

Question

Given: class CheckClass{ public static int checkValue (String s1, String s2){ return s1 length() "" s2.length(); } } and the code fragment: String[] strArray = new String [] {"Tiger", "Rat", "Cat", "Lion"}; //line n1 for (String s : strArray){ System.out.print (s + " "); } Which code fragment should be inserted at line n1 to enable the code to print Rat Cat Lion Tiger?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The code fragment provided is creating an array of Strings named strArray, which contains the values "Tiger", "Rat", "Cat", and "Lion". It then iterates over each element in the array using a for-each loop and prints each element to the console.

To print the values "Rat Cat Lion Tiger" instead of "Tiger Rat Cat Lion", we need to sort the array in alphabetical order. We can use the Arrays.sort() method to sort the elements in an array.

The Arrays.sort() method has several overloaded versions, but the one that takes an array and a Comparator is the most relevant for this question. A Comparator is an interface in Java that provides a way to compare two objects.

The code should create a Comparator object that can compare two strings based on their length. The CheckClass class has a static method called checkValue() that takes two strings and returns the difference between their lengths.

Option A is incorrect because the syntax for passing a method reference as a Comparator is wrong. It should be CheckClass::checkValue.

Option B is incorrect because it creates a new instance of CheckClass, which is unnecessary since checkValue() is a static method.

Option C is incorrect because it tries to call the checkValue() method on the CheckClass object, which is not possible since checkValue() is a static method.

Option D is the correct answer. It creates a method reference to the checkValue() method in the CheckClass class using the new operator. The double colon (::) operator is used to create a method reference in Java. The resulting Comparator object will compare two strings based on their length using the checkValue() method.

Therefore, the correct code fragment to insert at line n1 is:

less
Arrays.sort(strArray, CheckClass::new::checkValue);

This will sort the strArray in alphabetical order based on string length and output "Rat Cat Lion Tiger" to the console.