Upload
ganesh-samarthyam
View
959
Download
8
Embed Size (px)
Citation preview
OCP Java SE 8 Exam Sample Questions
JavaStreams
HariKiran&SGGanesh
Ques4onChoosethecorrectop4onbasedonthiscodesegment:"abracadabra".chars().distinct()
.peek(ch -> System. out .printf("%c ", ch)). sorted(); A.Itprints:“abcdr”B.Itprints:“abrcd”C.Itcrashesbythrowingajava.u=l.IllegalFormatConversionExcep=onD.Thisprogramterminatesnormallywithoutprin=nganyoutputintheconsole
h=ps://ocpjava.wordpress.com
AnswerChoosethecorrectop4onbasedonthiscodesegment:"abracadabra".chars().distinct()
.peek(ch -> System. out .printf("%c ", ch)). sorted(); A.Itprints:“abcdr”B.Itprints:“abrcd”C.Itcrashesbythrowingajava.u=l.IllegalFormatConversionExcep=onD.Thisprogramterminatesnormallywithoutprin4nganyoutputintheconsole
h=ps://ocpjava.wordpress.com
Explana4onD.Thisprogramterminatesnormallywithoutprin=nganyoutputintheconsoleSincethereisnoterminalopera=onprovided(suchascount,forEach,reduce,orcollect),thispipelineisnotevaluatedandhencethepeekdoesnotprintanyoutputtotheconsole.
h=ps://ocpjava.wordpress.com
Ques4onChoosethecorrectop4onbasedonthisprogram: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.ThisprogramresultsinacompilererrorB.Thisprogramprints:"aaaeaa"C.Thisprogramprints:"vdkdvr"D.Thisprogramprints:"avadakedavra"E.Thisprogramcrashesbythrowingajava.u=l.IllegalFormatConversionExcep=on
h=ps://ocpjava.wordpress.com
AnswerChoosethecorrectop4onbasedonthisprogram: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.ThisprogramresultsinacompilererrorB.Thisprogramprints:"aaaeaa"C.Thisprogramprints:"vdkdvr"D.Thisprogramprints:"avadakedavra"E.Thisprogramcrashesbythrowingajava.u=l.IllegalFormatConversionExcep=on
h=ps://ocpjava.wordpress.com
Explana4onB.Thisprogramprints:"aaaeaa“BecausetheConsonants::removeVowelsreturnstruewhenthereisavowelpassed,onlythosecharactersareretainedinthestreambythefiltermethod.Hence,thisprogramprints“aaaeaa”.
h=ps://ocpjava.wordpress.com
Ques4onChoosethebestop4onbasedonthisprogram: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.Thisprogramresultsinacompilererrorinlinemarkedwithcomment#1B.Thisprogramresultsinacompilererrorinlinemarkedwithcomment#2C.Thisprogramresultsinacompilererrorinlinemarkedwithcomment#3D.Thisprogramprints:falseE.Thisprogramprintsthestrings“do”,“re”,“mi”,“fa”,“so”,“la”,“=”,and“false”inseparatelinesF.Thisprogramprints:true
h=ps://ocpjava.wordpress.com
AnswerChoosethebestop4onbasedonthisprogram: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.Thisprogramresultsinacompilererrorinlinemarkedwithcomment#1B.Thisprogramresultsinacompilererrorinlinemarkedwithcomment#2C.Thisprogramresultsinacompilererrorinlinemarkedwithcomment#3D.Thisprogramprints:falseE.Thisprogramprintsthestrings“do”,“re”,“mi”,“fa”,“so”,“la”,“=”,and“false”inseparatelinesF.Thisprogramprints:true
h=ps://ocpjava.wordpress.com
Explana4onF.Thisprogramprints:trueThepredicatestr->str.length()>5returnsfalseforalltheelementsbecausethelengthofeachstringis2.Hence,thefilter()methodresultsinanemptystreamandthepeek()methoddoesnotprintanything.TheallMatch()methodreturnstrueforanemptystreamanddoesnotevaluatethegivenpredicate.Hencethisprogramprintstrue
h=ps://ocpjava.wordpress.com
Ques4onChoosethebestop4onbasedonthisprogram: 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.Compilererror:Cannotfindsymbol“sum”ininterfaceStream<Integer>B.Thisprogramprints:3C.Thisprogramprints:5D.Thisprogramprints:6E.Thisprogramcrashesbythrowingjava.lang.IllegalStateExcep=on
h=ps://ocpjava.wordpress.com
AnswerChoosethebestop4onbasedonthisprogram: 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.Compilererror:Cannotfindsymbol“sum”ininterfaceStream<Integer>B.Thisprogramprints:3C.Thisprogramprints:5D.Thisprogramprints:6E.Thisprogramcrashesbythrowingjava.lang.IllegalStateExcep=on
h=ps://ocpjava.wordpress.com
Explana4onA.Compilererror:Cannotfindsymbol“sum”ininterfaceStream<Integer>Dataandcalcula=onmethodssuchassum()andaverage()arenotavailableintheStream<T>interface;theyareavailableonlyintheprimi=vetypeversionsIntStream,LongStream,andDoubleStream.TocreateanIntStream,onesolu=onistousemapToInt()methodinsteadofmap()methodinthisprogram.IfmapToInt()wereused,thisprogramwouldcompilewithouterrors,andwhenexecuted,itwillprint6totheconsole.
h=ps://ocpjava.wordpress.com
Ques4onDeterminethebehaviourofthisprogram:
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.Thisprogramresultsinacompilererror:interfacescannotbedefinedinsideclassesB.Thisprogramresultsinacompilererror:@Func=onalInterfaceusedforLambdaFunc=onthatdefinestwoabstractmethodsC.Thisprogramresultsinacompilererrorincodemarkedwith#1:syntaxerrorD.Thisprogramcompileswithouterrors,andwhenrun,itprints100inconsole
h=ps://ocpjava.wordpress.com
AnswerDeterminethebehaviourofthisprogram:
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.Thisprogramresultsinacompilererror:interfacescannotbedefinedinsideclassesB.Thisprogramresultsinacompilererror:@Func=onalInterfaceusedforLambdaFunc=onthatdefinestwoabstractmethodsC.Thisprogramresultsinacompilererrorincodemarkedwith#1:syntaxerrorD.Thisprogramcompileswithouterrors,andwhenrun,itprints100inconsole
h=ps://ocpjava.wordpress.com
Explana4onD.isthecorrectanswerasthisprogramcompileswithouterrors,andwhenrun,itprints100inconsole.
Whyotherop4onsarewrong:
A. Aninterfacecanbedefinedinsideaclass
B. ThesignatureoftheequalsmethodmatchesthatoftheequalmethodinObjectclass;henceitisnotcountedasanabstractmethodinthefunc=onalinterface
C. ItisacceptabletoomittheparametertypewhenthereisonlyoneparameterandtheparameterandreturntypeareinferredfromtheLambdaFunc=onabstractmethoddeclara=onintapply(intj)
h=ps://ocpjava.wordpress.com
Ques4onChoosethebestop4onbasedonthisprogram:
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.Compilererror:improperlambdafunc=ondefini=onB.Thisprogramprints:eenymeenyminymoC.Thisprogramprints:mominymeenyeenyD.Thisprogramwillcompilefine,andwhenrun,willcrashbythrowingarun=meexcep=on.
h=ps://ocpjava.wordpress.com
AnswerChoosethebestop4onbasedonthisprogram:
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.Compilererror:improperlambdafunc=ondefini=onB.Thisprogramprints:eenymeenyminymoC.Thisprogramprints:mominymeenyeenyD.Thisprogramwillcompilefine,andwhenrun,willcrashbythrowingarun=meexcep=on.
h=ps://ocpjava.wordpress.com
Explana4onC.Thisprogramprints:mominymeenyeenyThisisaproperdefini=onofalambdaexpression.SincethesecondargumentofCollec=ons.sort()methodtakesthefunc=onalinterfaceComparatorandamatchinglambdaexpressionispassedinthiscode.Notethatsecondargumentiscomparedwiththefirstargumentinthelambdaexpression(str1,str2)->str2.compareTo(str1).Forthisreason,thecomparisonisperformedindescendingorder.
h=ps://ocpjava.wordpress.com
Ques4onWhatwillbetheresultofexecu4ngthiscodesegment?Stream.of("ace ", "jack ", "queen ", "king ", "joker ") .mapToInt(card -> card.length()) .filter(len -> len > 3) .peek(System.out::print) .limit(2);
A.Thiscodesegmentprints:jackqueenkingjokerB.Thiscodesegmentprints:jackqueenC.Thiscodesegmentprints:kingjokerD.Thiscodesegmentdoesnotprintanythingontheconsole
h=ps://ocpjava.wordpress.com
AnswerWhatwillbetheresultofexecu4ngthiscodesegment?Stream.of("ace ", "jack ", "queen ", "king ", "joker ") .mapToInt(card -> card.length()) .filter(len -> len > 3) .peek(System.out::print) .limit(2);
A.Thiscodesegmentprints:jackqueenkingjokerB.Thiscodesegmentprints:jackqueenC.Thiscodesegmentprints:kingjokerD.Thiscodesegmentdoesnotprintanythingontheconsole
h=ps://ocpjava.wordpress.com
Explana4onD.ThiscodesegmentdoesnotprintanythingontheconsoleThelimit()methodisanintermediateopera=onandnotaterminalopera=on.Sincethereisnoterminalopera=oninthiscodesegment,elementsarenotprocessedinthestreamandhenceitdoesnotprintanythingontheconsole.
h=ps://ocpjava.wordpress.com
Ques4onChoosethecorrectop4onbasedonthefollowingcodesegment: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.TheprogramresultsinacompilererrorinthelinemarkedwiththecommentCOMPARE_TOB.Theprogramprintsthefollowing:BrazilRussiaIndiaChinaC.Theprogramprintsthefollowing:BrazilChinaIndiaRussiaD.Theprogramprintsthefollowing:RussiaIndiaChinaBrazilE.Theprogramthrowstheexcep=onInvalidComparatorExcep=on
h=ps://ocpjava.wordpress.com
AnswerChoosethecorrectop4onbasedonthefollowingcodesegment: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.TheprogramresultsinacompilererrorinthelinemarkedwiththecommentCOMPARE_TOB.Theprogramprintsthefollowing:BrazilRussiaIndiaChinaC.Theprogramprintsthefollowing:BrazilChinaIndiaRussiaD.Theprogramprintsthefollowing:RussiaIndiaChinaBrazilE.Theprogramthrowstheexcep=onInvalidComparatorExcep=on
h=ps://ocpjava.wordpress.com
Explana4onC.Theprogramprintsthefollowing:BrazilChinaIndiaRussia.Forthesort()method,nullvalueispassedasthesecondargument,whichindicatesthattheelements’“naturalordering”shouldbeused.Inthiscase,naturalorderingforStringsresultsinthestringssortedinascendingorder.Notethatpassingnulltothesort()methoddoesnotresultinaNullPointerExcep=on.
h=ps://ocpjava.wordpress.com
Ques4onChoosethecorrectop4onbasedonthisprogram: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.Thisprogramdoesnotcompileandresultsincompilererror(s)B.Thisprogramprints:onetwothreeC.Thisprogramprints:11D.ThisprogramthrowsanIllegalArgumentExcep=on
h=ps://ocpjava.wordpress.com
AnswerChoosethecorrectop4onbasedonthisprogram: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.Thisprogramdoesnotcompileandresultsincompilererror(s)B.Thisprogramprints:onetwothreeC.Thisprogramprints:11D.ThisprogramthrowsanIllegalArgumentExcep=on
h=ps://ocpjava.wordpress.com
Explana4onC.Thisprogramprints:11Thisprogramcompileswithoutanyerrors.ThevariablewordspointtoastreamofStrings.ThecallmapToInt(String::length)resultsinastreamofIntegerswiththelengthofthestrings.Oneoftheoverloadedversionsofreduce()methodtakestwoarguments:Treduce(Tiden=ty,BinaryOperator<T>accumulator);Thefirstargumentistheiden=tyvalue,whichisgivenasthevalue0here.ThesecondoperandisaBinaryOperatormatchforthelambdaexpression(len1,len2)->len1+len2.Thereduce()methodthusaddsthelengthofallthethreestringsinthestream,whichresultsinthevalue11.
h=ps://ocpjava.wordpress.com
Ques4onChoosethecorrectop4onbasedonthiscodesegment:List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); ints.replaceAll(i -> i * i); // LINE System.out.println(ints);
A.Thiscodesegmentprints:[1,2,3,4,5]B.Thisprogramprints:[1,4,9,16,25]C.Thiscodesegmentthrowsjava.lang.UnsupportedOpera=onExcep=onD.ThiscodesegmentresultsinacompilererrorinthelinemarkedwiththecommentLINE
h=ps://ocpjava.wordpress.com
AnswerChoosethecorrectop4onbasedonthiscodesegment:List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); ints.replaceAll(i -> i * i); // LINE System.out.println(ints);
A.Thiscodesegmentprints:[1,2,3,4,5]B.Thisprogramprints:[1,4,9,16,25]C.Thiscodesegmentthrowsjava.lang.UnsupportedOpera=onExcep=onD.ThiscodesegmentresultsinacompilererrorinthelinemarkedwiththecommentLINE
h=ps://ocpjava.wordpress.com
Explana4onb)Thisprogramprints:[1,4,9,16,25]ThereplaceAll()method(addedinJava8totheListinterface)takesanUnaryOperatorastheargument.Inthiscase,theunaryoperatorsquarestheintegervalues.Hence,theprogramprints[1,4,9,16,25].
h=ps://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