SlideShare ist ein Scribd-Unternehmen logo
1 von 32
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 .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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
• 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

Weitere ähnliche Inhalte

Kürzlich hochgeladen

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 

Kürzlich hochgeladen (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 

Empfohlen

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Empfohlen (20)

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 

OCJP Samples Questions: Java streams

  • 1. OCP Java SE 8 Exam Sample Questions Java Streams Hari Kiran & S G Ganesh
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. • 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