Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
OCP Java SE 8 Exam
Sample Questions
Java Streams
Hari Kiran & S G Ganesh
Question
Choose the correct option based on this code segment:
"abracadabra".chars().distinct()
.peek(ch -> System. out .p...
Answer
Choose the correct option based on this code segment:
"abracadabra".chars().distinct()
.peek(ch -> System. out .pri...
Explanation
D . This program terminates normally without printing
any output in the console
Since there is no terminal ope...
Question
Choose the correct option based on this program:
class Consonants {
private static boolean removeVowels(int c) {
...
Answer
Choose the correct option based on this program:
class Consonants {
private static boolean removeVowels(int c) {
sw...
Explanation
B . This program prints: " aaaeaa“
Because the Consonants::removeVowels returns true
when there is a vowel pas...
Question
Choose the best option based on this program:
import java.util.stream.Stream;
public class AllMatch{
public stati...
Answer
Choose the best option based on this program:
import java.util.stream.Stream;
public class AllMatch{
public static ...
Explanation
F . This program prints: true
The predicate str -> str.length() > 5 returns false for all the
elements because...
Question
Choose the best option based on this program:
import java.util.regex.Pattern;
import java.util.stream.Stream;
pub...
Answer
Choose the best option based on this program:
import java.util.regex.Pattern;
import java.util.stream.Stream;
publi...
Explanation
A . Compiler error: Cannot find symbol “sum” in interface
Stream<Integer>
Data and calculation methods such as...
Question
Determine the behaviour of this program:
class LambdaFunctionTest {
@FunctionalInterface
interface LambdaFunction...
Answer
Determine the behaviour of this program:
class LambdaFunctionTest {
@FunctionalInterface
interface LambdaFunction {...
Explanation
D. is the correct answer as this program compiles without
errors, and when run, it prints 100 in console.
Why ...
Question
Choose the best option based on this program:
import java.util.*;
class Sort {
public static void main(String []a...
Answer
Choose the best option based on this program:
import java.util.*;
class Sort {
public static void main(String []arg...
Explanation
C . This program prints: mo miny meeny eeny
This is a proper definition of a lambda expression. Since the
seco...
Question
What will be the result of executing this code segment ?
Stream.of("ace ", "jack ", "queen ", "king ", "joker ")
...
Answer
What will be the result of executing this code segment ?
Stream.of("ace ", "jack ", "queen ", "king ", "joker ")
.m...
Explanation
D. This code segment does not print anything on the
console
The limit() method is an intermediate operation an...
Question
Choose the correct option based on the following code segment:
Comparator<String> comparer =
(country1, country2)...
Answer
Choose the correct option based on the following code segment:
Comparator<String> comparer =
(country1, country2) -...
Explanation
C. The program prints the following: Brazil China India
Russia.
For the sort() method, null value is passed as...
Question
Choose the correct option based on this program:
import java.util.stream.Stream;
public class Reduce {
public sta...
Answer
Choose the correct option based on this program:
import java.util.stream.Stream;
public class Reduce {
public stati...
Explanation
C. This program prints: 11
This program compiles without any errors. The
variable words point to a stream of S...
Question
Choose the correct option based on this code segment :
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
ints.re...
Answer
Choose the correct option based on this code segment :
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
ints.repl...
Explanation
b) This program prints: [1, 4, 9, 16, 25]
The replaceAll() method (added in Java 8 to the List
interface) take...
• Check out our latest book for
OCPJP 8 exam preparation
• http://amzn.to/1NNtho2
• www.apress.com/9781484218358
(download...
Upcoming SlideShare
Loading in …5
×

OCJP Samples Questions: Java streams

6,060 views

Published on

Are you a Java enthusiast and preparing for Java 8 certification exam (OCP Java SE 8)? Try out this Quiz on Java Streams introduced in Java 8

This quiz has answers with detailed explanation.

Published in: Software
  • Be the first to comment

  • Be the first to like this

OCJP Samples Questions: Java streams

  1. 1. OCP Java SE 8 Exam Sample Questions Java Streams Hari Kiran & S G Ganesh
  2. 2. Question Choose the correct option based on this code segment: "abracadabra".chars().distinct() .peek(ch -> System. out .printf("%c ", ch)). sorted(); A. It prints: “a b c d r” B. It prints: “a b r c d” C. It crashes by throwing a java.util.IllegalFormatConversionException D. This program terminates normally without printing any output in the console https://ocpjava.wordpress.com
  3. 3. Answer Choose the correct option based on this code segment: "abracadabra".chars().distinct() .peek(ch -> System. out .printf("%c ", ch)). sorted(); A. It prints: “a b c d r” B. It prints: “a b r c d” C. It crashes by throwing a java.util.IllegalFormatConversionException D. This program terminates normally without printing any output in the console https://ocpjava.wordpress.com
  4. 4. Explanation D . This program terminates normally without printing any output in the console Since there is no terminal operation provided (such as count , forEach , reduce, or collect ), this pipeline is not evaluated and hence the peek does not print any output to the console. https://ocpjava.wordpress.com
  5. 5. Question Choose the correct option based on this program: class Consonants { private static boolean removeVowels(int c) { switch(c) { case 'a': case 'e': case 'i': case 'o': case 'u': return true; } return false; } public static void main(String []args) { "avada kedavra".chars().filter(Consonants::removeVowels) .forEach(ch -> System.out.printf("%c", ch)); } } A. This program results in a compiler error B. This program prints: "aaaeaa" C. This program prints: "vd kdvr" D. This program prints: " avada kedavra " E. This program crashes by throwing a java.util.IllegalFormatConversionException https://ocpjava.wordpress.com
  6. 6. Answer Choose the correct option based on this program: class Consonants { private static boolean removeVowels(int c) { switch(c) { case 'a': case 'e': case 'i': case 'o': case 'u': return true; } return false; } public static void main(String []args) { "avada kedavra".chars().filter(Consonants::removeVowels) .forEach(ch -> System.out.printf("%c", ch)); } } A. This program results in a compiler error B. This program prints: "aaaeaa" C. This program prints: "vd kdvr" D. This program prints: " avada kedavra " E. This program crashes by throwing a java.util.IllegalFormatConversionException https://ocpjava.wordpress.com
  7. 7. Explanation B . This program prints: " aaaeaa“ Because the Consonants::removeVowels returns true when there is a vowel passed, only those characters are retained in the stream by the filter method. Hence, this program prints “aaaeaa”. https://ocpjava.wordpress.com
  8. 8. Question Choose the best option based on this program: import java.util.stream.Stream; public class AllMatch{ public static void main(String []args) { boolean result = Stream.of("do", "re", "mi", "fa", "so", "la", "ti") .filter(str -> str.length() > 5) // #1 .peek(System.out::println) // #2 .allMatch(str -> str.length() > 5); // #3 System.out.println(result); } } A. This program results in a compiler error in line marked with comment #1 B. This program results in a compiler error in line marked with comment #2 C. This program results in a compiler error in line marked with comment #3 D. This program prints: false E. This program prints the strings “do”, “re”, “mi”, “fa”, “so”, “la”, “ti”, and “false” in separate lines F. This program prints: true https://ocpjava.wordpress.com
  9. 9. Answer Choose the best option based on this program: import java.util.stream.Stream; public class AllMatch{ public static void main(String []args) { boolean result = Stream.of("do", "re", "mi", "fa", "so", "la", "ti") .filter(str -> str.length() > 5) // #1 .peek(System.out::println) // #2 .allMatch(str -> str.length() > 5); // #3 System.out.println(result); } } A. This program results in a compiler error in line marked with comment #1 B. This program results in a compiler error in line marked with comment #2 C. This program results in a compiler error in line marked with comment #3 D. This program prints: false E. This program prints the strings “do”, “re”, “mi”, “fa”, “so”, “la”, “ti”, and “false” in separate lines F. This program prints: true https://ocpjava.wordpress.com
  10. 10. Explanation F . This program prints: true The predicate str -> str.length() > 5 returns false for all the elements because the length of each string is 2. Hence, the filter() method results in an empty stream and the peek() method does not print anything. The allMatch() method returns true for an empty stream and does not evaluate the given predicate. Hence this program prints true https://ocpjava.wordpress.com
  11. 11. Question Choose the best option based on this program: import java.util.regex.Pattern; import java.util.stream.Stream; public class SumUse { public static void main(String []args) { Stream<String> words = Pattern.compile(“ “).splitAsStream(“a bb ccc”); System.out.println(words.map(word -> word.length()).sum()); } } A. Compiler error: Cannot find symbol “sum” in interface Stream<Integer> B. This program prints: 3 C. This program prints: 5 D. This program prints: 6 E. This program crashes by throwing java.lang.IllegalStateException https://ocpjava.wordpress.com
  12. 12. Answer Choose the best option based on this program: import java.util.regex.Pattern; import java.util.stream.Stream; public class SumUse { public static void main(String []args) { Stream<String> words = Pattern.compile(“ “).splitAsStream(“a bb ccc”); System.out.println(words.map(word -> word.length()).sum()); } } A. Compiler error: Cannot find symbol “sum” in interface Stream<Integer> B. This program prints: 3 C. This program prints: 5 D. This program prints: 6 E. This program crashes by throwing java.lang.IllegalStateException https://ocpjava.wordpress.com
  13. 13. Explanation A . Compiler error: Cannot find symbol “sum” in interface Stream<Integer> Data and calculation methods such as sum() and average() are not available in the Stream<T> interface; they are available only in the primitive type versions IntStream, LongStream, and DoubleStream. To create an IntStream , one solution is to use mapToInt() method instead of map() method in this program. If mapToInt() were used, this program would compile without errors, and when executed, it will print 6 to the console. https://ocpjava.wordpress.com
  14. 14. Question Determine the behaviour of this program: class LambdaFunctionTest { @FunctionalInterface interface LambdaFunction { int apply(int j); boolean equals(java.lang.Object arg0); } public static void main(String []args) { LambdaFunction lambdaFunction = i -> i * i; // #1 System.out.println(lambdaFunction.apply(10)); } } A. This program results in a compiler error: interfaces cannot be defined inside classes B. This program results in a compiler error: @FunctionalInterface used for LambdaFunction that defines two abstract methods C. This program results in a compiler error in code marked with #1: syntax error D. This program compiles without errors, and when run, it prints 100 in console https://ocpjava.wordpress.com
  15. 15. Answer Determine the behaviour of this program: class LambdaFunctionTest { @FunctionalInterface interface LambdaFunction { int apply(int j); boolean equals(java.lang.Object arg0); } public static void main(String []args) { LambdaFunction lambdaFunction = i -> i * i; // #1 System.out.println(lambdaFunction.apply(10)); } } A. This program results in a compiler error: interfaces cannot be defined inside classes B. This program results in a compiler error: @FunctionalInterface used for LambdaFunction that defines two abstract methods C. This program results in a compiler error in code marked with #1: syntax error D. This program compiles without errors, and when run, it prints 100 in console https://ocpjava.wordpress.com
  16. 16. Explanation D. is the correct answer as this program compiles without errors, and when run, it prints 100 in console. Why other options are wrong: A. An interface can be defined inside a class B. The signature of the equals method matches that of the equal method in Object class; hence it is not counted as an abstract method in the functional interface C. It is acceptable to omit the parameter type when there is only one parameter and the parameter and return type are inferred from the LambdaFunction abstract method declaration int apply(int j) https://ocpjava.wordpress.com
  17. 17. Question Choose the best option based on this program: import java.util.*; class Sort { public static void main(String []args) { List<String> strings = Arrays.asList("eeny ", "meeny ", "miny ", "mo "); Collections.sort(strings, (str1, str2) -> str2.compareTo(str1)); strings.forEach(string -> System.out.print(string)); } } A. Compiler error: improper lambda function definition B. This program prints: eeny meeny miny mo C. This program prints: mo miny meeny eeny D. This program will compile fine, and when run, will crash by throwing a runtime exception. https://ocpjava.wordpress.com
  18. 18. Answer Choose the best option based on this program: import java.util.*; class Sort { public static void main(String []args) { List<String> strings = Arrays.asList("eeny ", "meeny ", "miny ", "mo "); Collections.sort(strings, (str1, str2) -> str2.compareTo(str1)); strings.forEach(string -> System.out.print(string)); } } A. Compiler error: improper lambda function definition B. This program prints: eeny meeny miny mo C. This program prints: mo miny meeny eeny D. This program will compile fine, and when run, will crash by throwing a runtime exception. https://ocpjava.wordpress.com
  19. 19. Explanation C . This program prints: mo miny meeny eeny This is a proper definition of a lambda expression. Since the second argument of Collections.sort() method takes the functional interface Comparator and a matching lambda expression is passed in this code. Note that second argument is compared with the first argument in the lambda expression (str1, str2) -> str2.compareTo(str1) . For this reason, the comparison is performed in descending order. https://ocpjava.wordpress.com
  20. 20. Question What will be the result of executing this code segment ? Stream.of("ace ", "jack ", "queen ", "king ", "joker ") .mapToInt(card -> card.length()) .filter(len -> len > 3) .peek(System.out::print) .limit(2); A. This code segment prints: jack queen king joker B. This code segment prints: jack queen C. This code segment prints: king joker D. This code segment does not print anything on the console https://ocpjava.wordpress.com
  21. 21. Answer What will be the result of executing this code segment ? Stream.of("ace ", "jack ", "queen ", "king ", "joker ") .mapToInt(card -> card.length()) .filter(len -> len > 3) .peek(System.out::print) .limit(2); A. This code segment prints: jack queen king joker B. This code segment prints: jack queen C. This code segment prints: king joker D. This code segment does not print anything on the console https://ocpjava.wordpress.com
  22. 22. Explanation D. This code segment does not print anything on the console The limit() method is an intermediate operation and not a terminal operation. Since there is no terminal operation in this code segment, elements are not processed in the stream and hence it does not print anything on the console. https://ocpjava.wordpress.com
  23. 23. Question Choose the correct option based on the following code segment: Comparator<String> comparer = (country1, country2) -> country2.compareTo(country2); // COMPARE_TO String[ ] brics = {"Brazil", "Russia", "India", "China"}; Arrays.sort(brics, null); Arrays.stream(brics).forEach(country -> System.out.print(country + " ")); A. The program results in a compiler error in the line marked with the comment COMPARE_TO B. The program prints the following: Brazil Russia India China C. The program prints the following: Brazil China India Russia D. The program prints the following: Russia India China Brazil E. The program throws the exception InvalidComparatorException https://ocpjava.wordpress.com
  24. 24. Answer Choose the correct option based on the following code segment: Comparator<String> comparer = (country1, country2) -> country2.compareTo(country2); // COMPARE_TO String[ ] brics = {"Brazil", "Russia", "India", "China"}; Arrays.sort(brics, null); Arrays.stream(brics).forEach(country -> System.out.print(country + " ")); A. The program results in a compiler error in the line marked with the comment COMPARE_TO B. The program prints the following: Brazil Russia India China C. The program prints the following: Brazil China India Russia D. The program prints the following: Russia India China Brazil E. The program throws the exception InvalidComparatorException https://ocpjava.wordpress.com
  25. 25. Explanation C. The program prints the following: Brazil China India Russia. For the sort() method, null value is passed as the second argument, which indicates that the elements’ “natural ordering” should be used. In this case, natural ordering for Strings results in the strings sorted in ascending order. Note that passing null to the sort() method does not result in a NullPointerException. https://ocpjava.wordpress.com
  26. 26. Question Choose the correct option based on this program: import java.util.stream.Stream; public class Reduce { public static void main(String []args) { Stream<String> words = Stream.of("one", "two", "three"); int len = words.mapToInt(String::length).reduce(0, (len1, len2) -> len1 + len2); System.out.println(len); } } A. This program does not compile and results in compiler error(s) B. This program prints: onetwothree C. This program prints: 11 D. This program throws an IllegalArgumentException https://ocpjava.wordpress.com
  27. 27. Answer Choose the correct option based on this program: import java.util.stream.Stream; public class Reduce { public static void main(String []args) { Stream<String> words = Stream.of("one", "two", "three"); int len = words.mapToInt(String::length).reduce(0, (len1, len2) -> len1 + len2); System.out.println(len); } } A. This program does not compile and results in compiler error(s) B. This program prints: onetwothree C. This program prints: 11 D. This program throws an IllegalArgumentException https://ocpjava.wordpress.com
  28. 28. Explanation C. This program prints: 11 This program compiles without any errors. The variable words point to a stream of Strings. The call mapToInt(String::length) results in a stream of Integers with the length of the strings. One of the overloaded versions of reduce() method takes two arguments: T reduce(T identity, BinaryOperator<T> accumulator); The first argument is the identity value, which is given as the value 0 here. The second operand is a BinaryOperator match for the lambda expression (len1, len2) -> len1 + len2. The reduce() method thus adds the length of all the three strings in the stream, which results in the value 11. https://ocpjava.wordpress.com
  29. 29. Question Choose the correct option based on this code segment : List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); ints.replaceAll(i -> i * i); // LINE System.out.println(ints); A. This code segment prints: [1, 2, 3, 4, 5] B. This program prints: [1, 4, 9, 16, 25] C. This code segment throws java.lang.UnsupportedOperationException D. This code segment results in a compiler error in the line marked with the comment LINE https://ocpjava.wordpress.com
  30. 30. Answer Choose the correct option based on this code segment : List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); ints.replaceAll(i -> i * i); // LINE System.out.println(ints); A. This code segment prints: [1, 2, 3, 4, 5] B. This program prints: [1, 4, 9, 16, 25] C. This code segment throws java.lang.UnsupportedOperationException D. This code segment results in a compiler error in the line marked with the comment LINE https://ocpjava.wordpress.com
  31. 31. Explanation b) This program prints: [1, 4, 9, 16, 25] The replaceAll() method (added in Java 8 to the List interface) takes an UnaryOperator as the argument. In this case, the unary operator squares the integer values. Hence, the program prints [1, 4, 9, 16, 25]. https://ocpjava.wordpress.com
  32. 32. • Check out our latest book for OCPJP 8 exam preparation • http://amzn.to/1NNtho2 • www.apress.com/9781484218358 (download source code here) • https://ocpjava.wordpress.com (more ocpjp 8 resources here) http://facebook.com/ocpjava Linkedin OCP Java group

×