This chapter contains 85 questions and is designed to simulate a real OCP exam. While previous chapters were focused on a specific set of objectives, this chapter covers all of the objectives on the exam. We recommend you take this exam only after you score well on the questions in the individual chapters.
For this chapter, you should try to simulate the real exam experience as much as possible. This means setting aside 150 minutes of uninterrupted time to complete the test, as well as not looking at any reference material while taking the exam. If you don’t know an answer to a question, complete it as best you can and move on to the next question, just as you would on a real exam.
Remember, the exam permits writing material, such as a whiteboard. If you do not have a whiteboard handy, you can just use blank sheets of paper and a pencil. If you do well on this test, then you are hopefully ready to take the real exam. With that said, good luck!
Suppose the ResultSet is scrollable and contains 10 rows with values numbered from 1 to 10 in ascending order. What is true about the following? (Choose two.)
12: rs.beforeFirst();
13: System.out.println(rs.relative(5));
14: System.out.println(rs.getInt(1));
15: System.out.println(rs.relative(-10));
16: System.out.println(rs.getInt(1));
17: System.out.println(rs.relative(5));
18: System.out.print(rs.getInt(1));
What is the result of the following?
public class PiDay {
public static void main(String[] args) {
LocalDateTime pi = LocalDateTime.of(2017, 3, 14, 1, 59);
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("m.ddhhMM");
System.out.println(formatter.format(pi));
}
}
Which of the following are valid lambda expressions? (Choose three.)
What is the result of compiling and running the following application?
package names;
import java.util.*;
import java.util.function.*;
interface ApplyFilter {
void filter(List<String> input);
}
public class FilterBobs {
static Function<String,String> first = s ‐> {System.out.println(s); return s;};
static Predicate second = t -> "bob".equalsIgnoreCase(t);
public void process(ApplyFilter a, List<String> list) {
a.filter(list);
}
public static void main(String[] contestants) {
final List<String> people = new ArrayList<>();
people.add("Bob");
people.add("bob");
people.add("Jennifer");
people.add("Samantha");
final FilterBobs f = new FilterBobs();
f.process(q -> {
q.removeIf(second);
q.forEach(first);
}, people);
}
}
What is the output of the following?
public class Compete {
public static void main(String[] args) {
Stream<Integer> is = Stream.of(8, 6, 9);
Comparator<Integer> c = (a, b) ‐> b ‐ a; // r1
is.sorted(c).forEach(System.out::print); // r2
}
}
What is the output of the following application?
package tax;
public class Accountant {
class AddingException extends Exception {};
class DividingException extends Exception {};
class UnexpectedException extends RuntimeException {};
public void doTaxes() throws Throwable {
try {
throw new IllegalStateException();
} catch (AddingException | DividingException e) { // p1
System.out.println("Math Problem");
} catch (UnexpectedException | Exception f) { // p2
System.out.println("Unknown Error");
throw f;
}
}
public static void main(String[] numbers) throws Throwable {
try {
new Accountant().doTaxes();
} finally {
System.out.println("All done!");
}
}
}
What is the output of the following application?
1: package drawing;
2: interface HasHue {String getHue();}
3: enum COLORS implements HasHue {
4: red {
5: public String getHue() {return "FF0000";}
6: }, green {
7: public String getHue() {return "00FF00";}
8: }, blue {
9: public String getHue() {return "0000FF";}
10: }
11: }
12: class Book {
13: static void main(String[] pencils) {}
14: }
15: final public class ColoringBook extends Book {
16: final void paint(COLORS c) {
17: System.out.print("Painting: "+c.getHue());
18: }
19: final public static void main(String[] crayons) {
20: new ColoringBook().paint(COLORS.green);
21: }
22: }
How many of the following can fill in the blank to make this code compile?
public boolean isItMyBirthday(LocalDateTime dateTime) {
________________________________________
return now.getMonth() == dateTime.getMonth()
&& now.getDayOfMonth() == dateTime.getDayOfMonth();
}
Which two can independently fill in the blank to output No dessert today? (Choose two.)
import java.util.*;
public class Dessert {
public static void main(String[] yum) {
eatDessert(Optional.empty());
}
private static void eatDessert(Optional<String> opt) {
System.out.println(opt.__________);
}
}
What is the output of the following?
public class InitOrder {
{ System.out.print("1"); }
static { System.out.print("2"); }
public InitOrder() {
System.out.print("3");
}
public static void callMe() {
System.out.print("4");
}
public static void main(String[] args) {
callMe();
callMe();
System.out.print("5");
}
}
Which of the following cannot be instantiated directly by the caller using the constructor?
What design pattern or principle is used in this class?
public class Daffodil {
int height;
public Daffodil(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
}
What is the output of the following application? Assume the file system is available and able to be written to and read from.
package boat;
import java.io.*;
public class Cruise {
private int numPassengers = 1;
private transient String schedule = "NONE";
{numPassengers = 2;}
public Cruise() {
this.numPassengers = 3;
this.schedule = "Tropical Island";
}
public static void main(String... passengers) throws Exception {
try (ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("ship.txt"))) {
Cruise c = new Cruise();
c.numPassengers = 4;
c.schedule = "Casino";
o.writeObject(c);
}
try (ObjectInputStream i = new ObjectInputStream(
new FileInputStream("ship.txt"))) {
Cruise c = i.readObject();
System.out.print(c.numPassengers+","+c.schedule);
}
}
}
Which of the following are JDBC interfaces in the java.sql package?
Which of the following lambda expressions can be passed to a method that takes IntUnaryOperator as an argument? (Choose three.)
Which of the following statements about InputStream and Reader are correct? (Choose two.)
Fill in the blank so this code prints -1.
LocalDate xmas = LocalDate.of(2017, 12, 25);
LocalDate blackFriday = LocalDate.of(2017, 11, 24);
long monthsLeft = ChronoUnit.MONTHS.____________________;
System.out.println(monthsLeft);
Which statements about the following class are true?
package secure;
import java.io.*;
public class Login {
public void clearPassword(char[] password) {
for(int i=0; i<password.length; i++) {
password[i] = 0;
}
}
public String getPassword() {
Console c = System.console();
final char[] pass = c.readPassword("Enter your password: ");
StringBuilder sb = new StringBuilder();
for(char p : pass) {
sb.append(p);
}
clearPassword(pass);
return sb.toString();
}
public static void main(String[] webLogin) {
String pass = new Login().getPassword();
}
}
Which of the following can fill in the blank to print out the numbers 161, 183, and 201 in any order?
class Runner {
private int numberMinutes;
public Runner(int n) {
numberMinutes = n;
}
public int getNumberMinutes() {
return numberMinutes;
}
}
public class Marathon {
public static void main(String[] args) {
Stream<Runner> runners = Stream.of(new Runner(183),
new Runner(161), new Runner(201));
OptionalInt opt = runners.____________________;
}
}
What is the output of the following application?
1: package fruit;
2: enum Season {
3: SPRING(1), SUMMER(2), FALL(3), WINTER(4)
4: public Season(int orderId) {}
5: }
6: public class PickApples {
7: public static void main(String... orchard) {
8: final Season s = Season.FALL;
9: switch(s) {
10: case 3:
11: System.out.println("Time to pick!");
12: default:
13: System.out.println("Not yet!");
14: }
15: }
16: }
Which of the following expressions, inserted simultaneously into both blanks, allow the application to compile? (Choose three.)
package spooky;
import java.util.function.*;
abstract class Phantom {
public void bustLater(DoubleConsumer buster, double value) {
buster.accept(value);
}
}
public class Ghost extends Phantom {
public void bustNow(Consumer<Double> buster, double value) {
buster.accept(value);
}
void call() {
double value = 10;
bustNow(__________,value);
bustLater(__________,value);
}
}
What is the output of the following?
package counter;
import java.util.*;
public class CountResource extends ListResourceBundle {
private int count = 0;
@Override
protected Object[][] getContents() {
return new Object[][] { { "count", ++count } };
}
public static void main(String[] args) {
ResourceBundle rb = ResourceBundle.getBundle("counter.CountResource");
System.out.println(rb.getString("count") + " " + rb.getString("count"));
}
}
In most of the United States, daylight savings time ends on November 5, 2017 at 02:00 a.m., and we repeat that hour. What is the output of the following?
import java.time.*;
public class FallBack {
public static void main(String[] args) {
LocalDate localDate = LocalDate.of(2017, 10, 5);
LocalTime localTime = LocalTime.of(1, 0);
ZoneId zone = ZoneId.of("America/New_York");
ZonedDateTime z = ZonedDateTime.of(localDate, localTime, zone);
for (int i = 0; i < 6; i++)
z = z.plusHours(1);
System.out.println(z.getHour());
}
}
Assume the /environment directory exists and contains a file with a symbolic link to the /environment directory. In addition, assume all files within the directory are fully accessible. What is the result of executing the following program?
import java.nio.file.*;
import java.nio.file.attribute.*;
public class SearchEnvironment {
public static void accessFile(Path p, long timeEpoch) {
try {
Files.readAttributes(p, BasicFileAttributes.class)
.setTimes(null, null, FileTime.fromMillis(timeEpoch));
} catch (Throwable e) {
} finally {}
}
public static final void main(String[] unused) throws Exception {
Path w = Paths.get("/environment");
Files.walk(w)
.forEach(q -> accessFile(q,System.currentTimeMillis()));
}
}
Which command causes the following class to throw an AssertionError at runtime?
public class Watch {
private static final short DEFAULT_HOUR = 12;
private Watch() {
super();
}
int checkHour() {
assert DEFAULT_HOUR > 12;
return DEFAULT_HOUR;
}
public static void main(String... ticks) {
new Watch().checkHour();
}
}
What is the output of the following application?
package rope;
import java.util.concurrent.*;
import java.util.stream.IntStream;
public class Jump {
private static void await(CyclicBarrier b) {
try {
b.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
public static void main(String[] chalk) {
ExecutorService s = Executors.newFixedThreadPool(4);
final CyclicBarrier b = new CyclicBarrier(4,
() -> System.out.print("Jump!"));
IntStream
.iterate(1, q -> 2)
.limit(10)
.forEach(q -> s.execute(() ‐>await(b)));
s.shutdown();
}
}
What is the output of the following code snippet? Assume the two directories referenced both exist and are symbolic links to the same location within the file system.
if(Files.isSameFile("/salad/carrot", "/fruit/apple"))
System.out.println("Same!");
else System.out.println("Different!");
Which can fill in the blank JavaProgrammerCert class to compile and logically complete the code? (Choose two.)
class JavaProgrammerCert extends Exam {
private Exam oca;
private Exam ocp;
// assume getters and setters are here
______________________________________
}
public class Exam {
boolean pass;
protected boolean passed() {
return pass;
}
}
Which statements about overriding a method are correct? (Choose two.)
Which of the following can be independently inserted into the blank so the code can run without error for at least one SQL query?
private static void choices(Connection conn, String sql) throws SQLException {
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
____________________
}
}
Starting with DoubleBinaryOperator and going downward, fill in the values for the table.
Functional Interface | # Parameters |
DoubleBinaryOperator | |
LongToIntFunction | |
ToLongBiFunction | |
IntSupplier | |
ObjLongConsumer |
What is a possible output of the following?
LocalDate trainDay = LocalDate.of(2017, 5, 13);
LocalTime time = LocalTime.of(10, 0);
ZoneId zone = ZoneId.of("America/Los_Angeles");
ZonedDateTime zdt = ZonedDateTime.of(trainDay, time, zone);
Instant instant = zdt.toInstant();
instant = instant.plus(1, ChronoUnit.YEARS);
System.out.println(instant);
How many lines does the following output?
import java.util.stream.*;
class Blankie {
String color;
boolean isPink() {
return "pink".equals(color);
}
}
public class PreSchool {
public static void main(String[] args) {
Blankie b1 = new Blankie();
Blankie b2 = new Blankie();
b1.color = "pink";
Stream.of(b1, b2).filter(Blankie::isPink).forEach(System.out::println);
}
}
Which are the minimum changes needed to make this class immutable?
1: public class Tree {
2: String species;
3: public Tree(String species) {
4: this.species = species;
5: }
6: public String getSpecies() {
7: return species;
8: }
9: private final void setSpecies(String newSpecies) {
10: species = newSpecies;
11: }
12: }
Let’s say you needed to write a large List of Student objects to a data file. Which three concrete classes, chained together, would best accomplish this? (Choose three.)
Which statements when inserted independently will throw an exception at runtime? (Choose two.)
ArrayDeque<Integer> d = new ArrayDeque<>();
d.offer(18);
// INSERT CODE HERE
What is the output of the following code snippet?
11: Path x = Paths.get(".","song","..","/note");
12: Path y = Paths.get("/dance/move.txt");
13: x.normalize();
14: System.out.println(x.resolve(y));
15: System.out.println(y.relativize(x));
Given the following class, how many lines contain compilation errors?
package field;
import java.io.*;
class StungException extends Exception {}
class Suit implements Closeable {
public void close() throws IOException {}
}
public class BeeCatcher {
public static void main(String... bees) {
try (Suit s = new Suit(), Suit t = new Suit()) {
throw new StungException();
} catch (Exception e) {
} catch (StungException e) {
} finally {
}
}
}
What is the output of the following application?
package homework;
import java.util.*;
import java.util.stream.*;
public class QuickSolution {
public static int findFast(Stream<Integer> s) {
return s.findAny().get();
}
public static int findSlow(Stream<Integer> s) {
return s.parallel().findFirst().get();
}
public static void main(String[] pencil) {
Stream<Integer> s1 = Arrays.asList(1,2,3,4,5).stream();
Stream<Integer> s2 = Arrays.asList(1,2,3,4,5).stream();
int val1 = findFast(s1);
int val2 = findSlow(s2);
System.out.print(val1+" "+val2);
}
}
Given this property file used to load the Properties object props and this code snippet, what is the output?
mystery=bag
type=paper
18: System.out.print(props.getDefaultProperty("mystery", "?"));
19: System.out.print(" ");
20: System.out.print(props.getDefaultProperty("more", "?"));
Which statements about try-with-resources are true? (Choose two.)
How many lines fail to compile?
class Roller<E extends Wheel> {
public void roll(E e) { }
}
class Wheel { }
class CartWheel extends Wheel { }
public class RollingContest {
Roller<CartWheel> wheel1 = new Roller<CartWheel>();
Roller<Wheel> wheel2 = new Roller<CartWheel>();
Roller<? extends Wheel> wheel3 = new Roller<CartWheel>();
Roller<? extends Wheel> wheel4 = new Roller<Wheel>();
Roller<? super Wheel> wheel5 = new Roller<CartWheel>();
Roller<? super Wheel> wheel6 = new Roller<Wheel>();
}
Which are the minimum changes needed to properly implement the singleton pattern?
1: public class Bookmark {
2: private static Bookmark bookmark;
3: private int pageNumber;
4: static {
5: bookmark = new Bookmark();
6: }
7: public static Bookmark getInstance() {
8: return bookmark;
9: }
10: public int getPageNumber() {
11: return pageNumber;
12: }
13: public void setPageNumber(int newNumber) {
14: pageNumber = newNumber;
15: }
16: }
Given an updatable ResultSet that contains the following and this code, what does the code snippet output?
rs.afterLast();
rs.previous();
rs.updateInt(2, 10);
rs = stmt.executeQuery("select * from pens where color = 'red'");
while (rs.next()) {
System.out.println(rs.getInt(2));
}
Which statements describe a java.io stream class and cannot be applied to a java.util.stream.Stream class? (Choose three.)
Bill wants to create a program that reads all of the lines of all of his books using NIO.2. Unfortunately, Bill may have made a few mistakes writing his program. How many lines of the following class contain compilation errors?
1: package bookworm;
2: import java.io.*;
3: import java.nio.file.*;
4: public class ReadEverything {
5: public void readFile(Path p) {
6: try {
7: Files.readAllLines(p)
8: .parallel()
9: .forEach(System.out::println);
10: } catch (Exception e) {}
11: }
12: public void read(Path directory) throws Exception {
13: Files.walk(directory)
14: .filter(p -> File.isRegularFile(p))
15: .forEach(x -> readFile(x));
16: }
17: public static void main(String... books) throws IOException {
18: Path p = Path.get("collection");
19: new ReadEverything().read(p);
20: }
21: }
Assuming the following class is concurrently accessed by numerous threads, which statement about the CountSheep class is correct?
package fence;
import java.util.concurrent.atomic.*;
public class CountSheep {
private static AtomicInteger counter = new AtomicInteger();
private Object lock = new Object();
public synchronized int increment1() {
return counter.incrementAndGet();
}
public static synchronized int increment2() {
return counter.getAndIncrement();
}
public int increment3() {
synchronized(lock) {
return counter.getAndIncrement();
}
}
}
Which of the following are not required parameters for the NIO.2 Files.find() method? (Choose two.)
Which statements are correct? (Choose two.)
What is the output of the following code snippet, assuming none of the files referenced exist within the file system?
Path t1 = Paths.get("/sky/.././stars.exe");
Path t2 = Paths.get("/stars.exe");
Path t3 = t1.resolve(t2);
boolean b1 = t1.equals(t2);
boolean b2 = t1.normalize().equals(t2);
boolean b3 = Files.isSameFile(t1.normalize(),t2);
boolean b4 = Files.isSameFile(t2,t3);
System.out.print(b1+","+b2+","+b3+","+b4);
Let’s say we have a Reader instance that will produce the characters with the numeric values {1,2,3,4,5,6,7}. Which of the following are possible outcomes of executing the checkLottoNumbers() method with this Reader instance? (Choose two.)
23: public String checkLottoNumbers(Reader r) throws IOException {
24: r.read();r.skip(1);
25: r.mark(5);
26: r.skip(1);
27: r.reset();
28: return r.read()+"-"+r.read(new char[5]);
29: }
Fill in the blanks: The name of the abstract method in the Function interface __________ is , while the name of the abstract method in the Consumer interface is__________ .
Assuming the following program is executed with assertions enabled, which is the first line to throw an exception at runtime?
1: package school;
2: public class Teacher {
3: public int checkClasswork(int choices) {
4: assert choices++==10 : 1;
5: assert true!=false : new StringBuilder("Answer2");
6: assert(null==null) : new Object();
7: assert ++choices==11 : "Answer4";
8: assert 2==3 : "";
9: return choices;
10: }
11: public final static void main(String... students) {
12: try {
13: new Teacher().checkClasswork(10);
14: } catch (Error e) {
15: System.out.print("Bad idea");
16: throw e;
17: }
18: }
19: }
Which of the following are valid functional interfaces in the java.util.function package? (Choose three.)
Which statements about the following class are correct? (Choose two.)
package knowledge;
class InformationException extends Exception {}
public class LackOfInformationException extends InformationException {
public LackOfInformationException() { // t1
super("");
}
public LackOfInformationException(String s) { // t2
this(new Exception(s));
}
public LackOfInformationException(Exception c) { // t3
super();
}
@Override public String getMessage() {
return "lackOf";
}
}
How many changes do you need to make in order for this code to compile?
public class Ready {
private static double getNumber() {
return .007;
}
public static void math() {
Supplier<double> s = Ready:getNumber;
double d = s.get();
System.out.println(d);
}
}
Which statement about the following class is correct?
package robot;
import java.util.concurrent.*;
public class PassButter extends RecursiveTask<String> { // j1
final int remainder;
public PassButter(int remainder) { // j2
this.remainder = remainder;
}
@Override
protected String compute() {
if (remainder <= 1)
return "1";
else {
PassButter otherTask = new PassButter(remainder - 1);
String otherValue = otherTask.fork().join(); // j3
return otherValue
+ new PassButter(remainder - 2).compute();
}
}
public static void main(String[] purpose) {
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<?> task = new PassButter(10);
System.out.print(pool.invoke(task));
pool.shutdown();
}
}
Which can fill in the blank so this code outputs true?
import java.util.function.*;
import java.util.stream.*;
public class HideAndSeek {
public static void main(String[] args) {
Stream<Boolean> hide = Stream.of(true, false, true);
Predicate<Boolean> pred = b ‐> b;
boolean found = hide.filter(pred).__________(pred);
System.out.println(found);
}
}
Given the following code, Java will try to find a matching resource bundle. Which order will Java search to find a match?
Locale.setDefault(new Locale("en"));
ResourceBundle.getBundle("AB", new Locale("fr"));
What is the result of the following?
Set<Integer> dice = new TreeSet<>();
dice.add(6);
dice.add(6);
dice.add(4);
dice.stream().filter(n -> n != 4).forEach(System.out::println).count();
Given the following two property files in the pod package, what does the following class output?
pod.container.properties
name=generic
number=2
pod.container_en.properties
name=Docker
type=container
package pod;
import java.util.*;
public class WhatKind {
public static void main(String[] args) {
Locale.setDefault(new Locale("ja"));
ResourceBundle rb = ResourceBundle.getBundle("pod.container");
String name = rb.getString("name"); // r1
String type = rb.getString("type"); // r2
System.out.println(name + " " + type); }
}
What is the result of the following?
import java.util.stream.*;
public class StreamOfStreams {
public static void main(String[] args) {
Integer result =
Stream.of(getNums(9, 8), getNums(22, 33)) // c1
.filter(x -> !x.isEmpty()) // c2
.flatMap(x -> x) // c3
.max((a, b) -> a ‐ b) // c4
.get();
System.out.println(result);
}
private static Stream<Integer> getNums(int num1, int num2) {
return Stream.of(num1, num2);
}
}
Which of the following shows a valid Locale format? (Choose two.)
What is true of the following if the music database exists and contains a songs table with one row when run using a JDBC 4.0 driver? (Choose two.)
import java.sql.*;
public class Music {
public static void main(String[] args) throws Exception {
String url = "jdbc:derby:music";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
stmt.execute("update songs set name = 'The New Song'");
}
}
How many of the following pairs of values can fill in the blanks to comply with the contract of the hashCode() and equals() methods?
class Sticker {
@Override
public int hashCode() {
return _______________ ;
}
@Override
public boolean equals(Sticker o) {
return _______________;
}
}
What is the output of the following application?
package winter;
abstract class TShirt {
abstract int insulate();
public TShirt() {
System.out.print("Starting...");
}
}
public class Wardrobe {
abstract class Sweater extends TShirt {
int insulate() {return 5;}
}
private static void dress() {
class Jacket extends Sweater { // v1
int insulate() {return 10;}
};
final TShirt outfit = new Jacket() { // v2
int insulate() {return 20;}
};
System.out.println("Insulation:"+outfit.insulate());
}
public static void main(String... snow) {
new Wardrobe().dress();
}
}
Which statements about the following application are true?
1: package armory;
2: import java.util.function.*;
3: class Shield {}
4: public class Sword {
5: public class Armor {
6: int count;
7: public final Function<Shield,Sword,Armor> dress = (h,w) ‐> new Armor();
8: public final IntSupplier<Integer> addDragon = () ‐> count++;
9: }
10: public static void main(String[] knight) {
11: final Armor a = new Armor();
12: a.dress.apply(new Shield(), new Sword());
13: a.addDragon.getAsInt();
14: }
15: }
Which two conditions best describe a thread that appears to be active but is perpetually stuck and never able to finish its task? (Choose two.)
Which statements are true about the following date/times? (Choose two.)
2017-04-01T17:00+03:00[Africa/Nairobi]
2017-04-01T10:00-05:00[America/Panama]
What is true about the following?
import java.util.*;
public class Yellow {
public static void main(String[] args) {
List list = Arrays.asList("Sunny");
method(list); // c1
}
private static void method(Collection<?> x) { //c2
x.forEach(a -> {}); // c3
}
}
What is true about the following code? (Choose two.)
public static void main(String[] args) throws Exception {
String url = "jdbc:derby:hats;create=true";
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
stmt.executeUpdate( "CREATE TABLE caps (name varchar(255), size varchar(1))");
} finally {
conn.close();
stmt.close();
}
}
How many lines of the following application contain a compilation error?
package puzzle;
final interface Finder {
default long find() {return 20;}
}
abstract class Wanda {
abstract long find();
}
final class Waldo extends Wanda implements Finder {
long find() {return 40;}
public static final void main(String[] pictures) {
final Finder f = new Waldo();
System.out.print(f.find());
}
}
What is the output of the following?
1: package reader;
2: import java.util.stream.*;
3:
4: public class Books {
5: public static void main(String[] args) {
6: IntStream pages = IntStream.of(200, 300);
7: long total = pages.sum();
8: long count = pages.count();
9: System.out.println(total + "-" + count);
10: }
11: }
What is the output of executing the following code snippet?
30: ExecutorService e = Executors.newSingleThreadExecutor();
31: Runnable r1 = () -> Stream.of(1,2,3).parallel();
32: Callable r2 = () -> Stream.of(4,5,6).parallel();
33:
34: Future<Stream> f1 = e.submit(r1);
35: Future<Stream> f2 = e.submit(r2);
36:
37: Stream<Integer> s = Stream.of(f1.get(),f2.get())
38: .flatMap(p -> p)
39: .parallelStream();
40:
41: ConcurrentMap<Boolean,List<Integer>> r =
42: s.collect(Collectors.groupingByConcurrent(i -> i%2==0));
43: System.out.println(r.get(false).size()+" "+r.get(true).size());
Fill in the blanks: If your application is__________ , it must first have been __________ with respect to supporting multiple languages.
Which statement about the following class is true? Assume the file system is available and able to be modified.
package forest;
import java.io.File;
public class CreateTree {
public boolean createTree(String tree) {
if(new File(tree).exists()) {
return true;
} else {
return new File(tree).mkdir();
}
}
public static void main(String[] seeds) {
final CreateTree creator = new CreateTree();
System.out.print(creator.createTree("/woods/forest"));
}
}
What does the following print?
1: class SmartWatch extends Watch {
2: private String getType() { return "smart watch"; }
3: public String getName() {
4: return getType() + ",";
5: }
6: }
7: public class Watch {
8: private String getType() { return "watch"; }
9: public String getName(String suffix) {
10: return getType() + suffix;
11: }
12: public static void main(String[] args) {
13: Watch watch = new Watch();
14: Watch smartWatch = new SmartWatch();
15: System.out.print(watch.getName(","));
16: System.out.print(smartWatch.getName(""));
17: }
18: }
In most of the United States, daylight savings time ends on November 5, 2017 at 02:00 a.m., and we repeat that hour. What is the output of the following?
import java.time.*;
public class FallBack {
public static void main(String[] args) {
LocalDate localDate = LocalDate.of(2017, Month.NOVEMBER, 5);
LocalTime localTime = LocalTime.of(1, 0);
ZoneId zone = ZoneId.of("America/New_York");
ZonedDateTime z = ZonedDateTime.of(localDate, localTime, zone);
for (int i = 0; i < 6; i++)
z = z.plusHours(1);
System.out.println(z.getHour());
}
}
Which statements about the following application are true?
package party;
import java.util.concurrent.*;
public class Plan {
private ExecutorService service = Executors.newCachedThreadPool();
public void planEvents() {
service.scheduleWithFixedDelay(
() -> System.out.print("Check food stock"),
1, TimeUnit.HOURS);
service.scheduleAtFixedRate(
() -> System.out.print("Check drink stock"),
1, 1000, TimeUnit.SECONDS);
service.execute(() -> System.out.print("Take out trash"));
}
}
Which of the following classes are checked exception? (Choose three.)
Which of the following are valid functional interfaces? (Choose two.)
How many of the following could be valid JDBC URL formats for an imaginary driver named magic and a database named box?
What is the output of the following?
Stream<String> s = Stream.of("speak", "bark", "meow", "growl");
Map<Integer, String> map = s.collect(toMap(String::length, k ‐> k));
System.out.println(map.size() + " " + map.get(4));
What is the output of the following application?
package music;
interface DoubleBass {
void strum();
default int getVolume() {return 5;}
}
interface BassGuitar {
void strum();
default int getVolume() {return 10;}
}
class ElectricBass implements DoubleBass, BassGuitar {
@Override public void strum() {System.out.print("A");}
}
public class RockBand {
public static void main(String[] strings) {
final class MyElectricBass extends ElectricBass {
public void strum() {System.out.print("E");}
}
}
}
Which NIO.2 Files methods return a Stream? (Choose three.)