Java OCA OCP Practice Question 1985

Question

What is the output of the following application?.

package mypkg; //w ww. j a va  2s .  co m
import java.util.*; 
public class Main { 
   public String concat1(List<String> values) { 
      return values.parallelStream() 
            .reduce("a", 
                  (x,y)->x+y, 
                  String::concat); 
   } 
   public String concat2(List<String> values) { 
      return values.parallelStream() 
            .reduce((w,z)->z+w).get(); 
   } 
   public static void main(String... questions) { 
      Main c = new Main(); 
      List<String> list = Arrays.asList("Cat","Hat"); 
      String x = c.concat1(list); 
      String y = c.concat2(list); 
      System.out.print(x+" "+y); 
   } 
} 
A.   aCataHat HatCat
B.  CatHat CatHat
C.  The code does not compile because concat1() returns an Optional.
D.  The code does not compile for a different reason.


A.

Note

The code compiles and runs without issue.

The three-argument reduce() method returns a generic type, while the one-argument reduce() method returns an Optional.

The concat1() method is passed an identity "a", which it applies to each element, resulting in the reduction to aCataHat.

The lambda expression in the concat2() method reverses the order of its inputs, leading to a value of HatCat.

Therefore, Option A is the correct answer.




PreviousNext

Related