Java OCA OCP Practice Question 2208

Question

How many lines does the following output?

import java.util.stream.*; 


class Rectangle { 
   String color; //from  w w  w.j  a v  a  2  s.  com
   boolean isPink() { 
      return "pink".equals(color); 
   } 
} 
public class Main { 
   public static void main(String[] args) { 
     Rectangle b1 = new Rectangle(); 
     Rectangle b2 = new Rectangle(); 
     b1.color = "pink"; 
     Stream.of(b1, b2).filter(Rectangle::isPink).forEach(System.out::println); 
   } 
} 
  • A. None
  • B. One
  • C. Two
  • D. The code does not compile.
  • E. The code compiles but throws an exception at runtime.


B.

Note

First we create two Rectangle objects.

One of them has the color pink and the other leaves it as the default value of null.

When the stream intermediate operation runs, it calls the isPink() method twice, returning true and false respectively.

Only the first one goes on to the terminal operation and is printed, making Option B correct.




PreviousNext

Related