SUGGESTED WORKFLOW:

Stage 1: 
Click here to expand

Do the warm-up exercises first by going through Flashcards for each individual Exam Objective (360+ questions covering 56 subjects in total; meanwhile, Knowledge Banks and assorted Prep Notes provide whatever you need to know for the exam):

1. Java Class Design Flashcards + Knowledge Bank

  • Implement encapsulation
  • Implement inheritance including visibility modifiers and composition
  • Implement polymorphism
  • Override hashCode, equals, and toString methods from Object class
  • Create and use singleton classes and immutable classes
  • Develop code that uses static keyword on initialize blocks, variables, methods, and classes

2. Advanced Java Class Design Flashcards + Knowledge Bank

  • Develop code that uses abstract classes and methods
  • Develop code that uses the final keyword
  • Create inner classes including static inner class, local class, nested class, and anonymous inner class
  • Use enumerated types including methods, and constructors in an enum type
  • Develop code that declares, implements and/or extends interfaces and use the @Override annotation
  • Create and use Lambda expressions

3. Generics and Collections Flashcards + Knowledge Bank

  • Create and use a generic class
  • Create and use ArrayList, TreeSet, TreeMap, and ArrayDeque objects
  • Use java.util.Comparator and java.lang.Comparable interfaces
  • Collections Streams and Filters
  • Iterate using forEach methods of Streams and List
  • Describe Stream interface and Stream pipeline
  • Filter a collection by using lambda expressions
  • Use method references with Streams

4. Lambda Built-in Functional Interfaces Flashcards + Knowledge Bank

  • Use the built-in interfaces included in the java.util.function package such as Predicate, Consumer, Function, and Supplier
  • Develop code that uses primitive versions of functional interfaces
  • Develop code that uses binary versions of functional interfaces
  • Develop code that uses the UnaryOperator interface

5. Java Stream API Flashcards + Knowledge Bank

  • Develop code to extract data from an object using peek() and map() methods including primitive versions of the map() method
  • Search for data by using search methods of the Stream classes including findFirst, findAny, anyMatch, allMatch, noneMatch
  • Develop code that uses the Optional class
  • Develop code that uses Stream data methods and calculation methods
  • Sort a collection using Stream API
  • Save results to a collection using the collect method and group/partition data using the Collectors class
  • Use flatMap() methods in the Stream API

6. Exceptions and Assertions Flashcards + Knowledge Bank + Prep Notes on TWRs

  • Use try-catch and throw statements
  • Use catch, multi-catch, and finally clauses
  • Use Autoclose resources with a try-with-resources statement
  • Create custom exceptions and Auto-closeable resources
  • Test invariants by using assertions

7. Use Java SE 8 Date/Time API Flashcards + Knowledge Bank

  • Create and manage date-based and time-based events including a combination of date and time into a single object using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration
  • Work with dates and times across timezones and manage changes resulting from daylight savings including Format date and times values
  • Define and create and manage date-based and time-based events using Instant, Period, Duration, and TemporalUnit

8. Java I/O Fundamentals Flashcards + Knowledge Bank

  • Read and write data from the console
  • Use BufferedReader, BufferedWriter, File, FileReader, FileWriter, FileInputStream, FileOutputStream, ObjectOutputStream, ObjectInputStream, and PrintWriter in the java.io package.

9. Java File I/O (NIO.2) Flashcards + Knowledge Bank

  • Use Path interface to operate on file and directory paths
  • Use Files class to check, read, delete, copy, move, manage metadata of a file or directory
  • Use Stream API with NIO.2

10. Java Concurrency Flashcards + Knowledge Bank

  • Create worker threads using Runnable, Callable and use an ExecutorService to concurrently execute tasks
  • Identify potential threading problems among deadlock, starvation, livelock, and race conditions
  • Use synchronized keyword and java.util.concurrent.atomic package to control the order of thread execution
  • Use java.util.concurrent collections and classes including CyclicBarrier and CopyOnWriteArrayList
  • Use parallel Fork/Join Framework
  • Use parallel Streams including reduction, decomposition, merging processes, pipelines and performance.

11. Building Database Applications with JDBC Flashcards + Knowledge Bank + Prep Notes on JDBC

  • Describe the interfaces that make up the core of the JDBC API including the Driver, Connection, Statement, and ResultSet interfaces and their relationship to provider implementations
  • Identify the components required to connect to a database using the DriverManager class including the JDBC URL
  • Submit queries and read results from the database including creating statements, returning result sets, iterating through the results, and properly closing result sets, statements, and connections

12. Localization Flashcards + Knowledge Bank

  • Read and set the locale by using the Locale object
  • Create and read a Properties file
  • Build a resource bundle for each locale and load a resource bundle in an application
Stage 2:
Click here to expand
Take grouped tests for each individual Exam Objective

1. Java Class Design, Stage 2 Problems

2. Advanced Java Class Design, Stage 2 Problems
3. Generics and Collections, Stage 2 Problems
4. Lambda Built-in Functional Interfaces, Stage 2 Problems
5. Java Stream API, Stage 2 Problems
6. Exceptions and Assertions, Stage 2 Problems
7. Use Java SE 8 Date/Time API, Stage 2 Problems
8. Java I/O Fundamentals, Stage 2 Problems
9. Java File I/O (NIO.2), Stage 2 Problems
10. Java Concurrency, Stage 2 Problems
11. Building Database Applications with JDBC, Stage 2 Problems
12. Localization, Stage 2 Problems

Stage 3:
Click here to expand
Finally,¬†run through the following practice problems, which have been modelled after¬†real exam questions: they fully mimic their structure, target the same objectives and contain same traps. The only things that have been changed are custom class names, identifiers and literals. So master underlying concepts, and you’ll pass the OCP exam with flying colors.

To take Stage 3 tests in online format click here.

 

Stage 3 Problem 1 (view answer and explanation)

Given that /fish.txt and /cats/tiger.txt are accessible, and the code fragment:

Path source = Paths.get("/fish.txt");
Path target = Paths.get("/cats/tiger.txt");
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
Files.delete(source);

Which statement is true?

A. The fish.txt file content is replaced by the tiger.txt file content and the tiger.txt file is deleted.
B. The tiger.txt file content is replaced by the fish.txt file content and an exception is thrown.
C. The file fish.txt is moved to the /cats directory.
D. A FileAlreadyExistsException is thrown at runtime.

Stage 3 Problem 2 (view answer and explanation)

Given the class definitions:

class Plant {
    public String brew(String msg) {
        return msg;
    }
}
class Coffee extends Plant {
    public String brew(String msg) {
        return msg.replace('a', 'e');
    }
}
class Arabica extends Coffee {
    public String brew(String msg) {
        return msg.substring(2);
    }
}

And the code fragment of the main() method,

List<Plant> cup = new ArrayList<Plant>();
cup.add(new Plant());
cup.add(new Coffee());
cup.add(new Arabica());
for (Plant item : cup) {
        System.out.println(item.brew("Java"));
}

What is the result?

A. Java
Java
Java
B. Java
Jeve
va
C. Java
Jeve
ve
D. Compilation fails

Stage 3 Problem 3 (view answer and explanation)

Given the code fragment:

BiFunction<Integer, Double, Integer> value = (p1, p2) -> p1 + p2;   // line n1
System.out.println(value.apply(1, 1.5));                            // line n2

What is the result?

A. 2
B. 2.5
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2

Stage 3 Problem 4 (view answer and explanation)

Given the code fragment:

List<Integer> numbers = Arrays.asList(1, 2, 3);
numbers.stream()
       .map(num -> num*2)                //line n1
       .peek(System.out::print)          //line n2
       .count();

What is the result?

A. 246
B. The code produces no output.
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2

Stage 3 Problem 5 (view answer and explanation)

Which two statements are true about localizing an application?

A. Support for new regional languages does not require recompilation of the code.
B. Textual elements (messages and GUI labels) are hard-coded in the code.
C. Language- and region-specific programs are created using localized data.
D. Resource bundle files include data and currency information.
E. Language codes use lowercase letters and region codes use uppercase letters.

Stage 3 Problem 6 (view answer and explanation)

Given the code fragments:

class Caller implements Callable<String> {
    String str;
    public Caller (String str) {
        this.str = str;
    }
    public String call() throws Exception {
        return str.concat ("Caller");
    }
}
class Runner implements Runnable {
    String str;
    public Runner (String str) {
        this.str = str;
    }
    public void run() {
        System.out.println (str.concat ("Runner"));
    }
}

and

public static void main (String[] args) throws InterruptedException, ExecutionException {
    ExecutorService exec = Executors.newFixedThreadPool(2);
    Future f1 = exec.submit(new Caller ("Call "));
    Future f2 = exec.submit(new Runner ("Run "));
    String str1 = (String) f1.get();
    String str2 = (String) f2.get();                 //line n1
    System.out.println(str1+ " : " + str2);
}

What is the result?

A. The program prints:
Run Runner
Call Caller : null
And the program does not terminate.
B. The program terminates after printing:
Run Runner
Call Caller : Run
C.  A compilation error occurs at line n1
D. An exception is thrown at run time

Stage 3 Problem 7 (view answer and explanation)

Given the code fragments:

class OS {
    String name;
    OS (String name) {
        this.name = name;
    }
}

and

List<OS> list = Arrays.asList(
    new OS("Windows "),
    new OS("Solaris "),
    new OS("Linux ")
);
Stream<OS> creek = list.stream();
//line n1

Which should be inserted at line n1 to print Windows Solaris Linux ?

A. creek.forEach(System.out::print);
B. creek.map(a -> a.name).forEach(System.out::print);
C. creek.map(a -> a).forEachOrdered(System.out::print);
D. creek.forEachOrdered(System.out::print);

Stage 3 Problem 8 (view answer and explanation)

Given the code fragment:

class Test implements Runnable {
    String fileName;
    public Test(String fileName) { this.fileName = fileName; }
    public void run() {System.out.println(fileName);}
    public static void main (String[] args) throws IOException, InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        Stream<Path> listOfFiles = Files.walk(Paths.get("C:\\Try_Java"));
        listOfFiles.forEach(e -> {
            exec.execute(new Test(e.getFileName().toString()));          // line n1
        });
        exec.shutdown();
        exec.awaitTermination(365, TimeUnit.DAYS);                       // line n2
    }
}

The C:\Try_Java directory exists and contains a list of files. What is the result?

A. The program throws a runtime exception at line n2.
B. The program prints files names concurrently.
C. The program prints files names sequentially.
D. A compilation error occurs at line n1.

Stage 3 Problem 9 (view answer and explanation)

Given:

final class Mouth {           //line n1
//line n2
    public void open() {
        System.out.print("Open ");
    }
}
class Test {
    public static void main (String [] args) throws Exception {
        try(Mouth f = new Mouth()) {
            f.open();
        }
    }
}

Which two modifications enable the code to print Open Close?

A. Replace line n1 with:
class Mouth implements AutoCloseable {
B. Replace line n1 with:
class Mouth extends Closeable {
C. Replace line n1 with:
class Mouth extends Exception {
D. At line n2, insert:
final void close() { System.out.print(“Close”); }
E. At line n2, insert:
public void close() throws IOException { System.out.print(“Close”); }

Stage 3 Problem 10 (view answer and explanation)

Given the code fragment:

List<Integer> num = Arrays.asList(1, 2);
UnaryOperator<Double> unop = x -> x + 1.0;
num.replaceAll(unop);
num.forEach(x -> System.out.println(x));

What is the result?

A. 2.0
3.0
B. 1
C. A compilation error occurs
D. A NumberFormatException is thrown at run time

Stage 3 Problem 11 (view answer and explanation)

Given:

class Dog {
    String name;
    String breed;
    public Dog (String name, String breed) {
        this.name = name;
        this.breed = breed;
    }
    public String getName() { return name; }
    public String getBreed() { return breed; }
}

and the code fragment:

List<Dog> kennels = Arrays.asList (
    new Dog ("Oliver", "Collie"),
    new Dog ("Sam", "Beagle"),
    new Dog ("Jack", "Beagle"),
kennels.stream()
// line n1
       .collect(Collectors.toList());

Which code fragment, when inserted at line n1, sorts the list of dogs in descending order of breed and then ascending order of name?

A. .sorted(Comparator.comparing(Dog::getBreed).reversed().thenComparing(Dog::getName))
B. .sorted(Comparator.comparing(Dog::getBreed).thenComparing(Dog::getName))
C. .map(Dog::getBreed).sorted(Comparator.reverseOrder())
D. .map(Dog::getBreed).sorted(Comparator.reverseOrder().map(Dog::getName).reversed())

Stage 3 Problem 12 (view answer and explanation)

Given:

interface Laughable {Joke crackJoke(String joke); }
class Joke {
    private String joke;
    public Joke(String joke) {
        this.joke = joke;
    }
}

Which code fragment creates an instance of Joke?

A. Joke hello = Joke("MyJoke")::new;
B. Joke hello = Joke::new;
Joke oneMore = hello::crackJoke("MyJoke");
C. Laughable joker = Joke::new;
Joke oneMore = joker.crackJoke("MyJoke");
D. Joke oneMore = Laughable::new::crackJoke("MyJoke");

Stage 3 Problem 13 (view answer and explanation)

Given:

public final class WordPress {
    public void login() {}
}
piblic class Post {
    public final void write(int words, int pix) {}
    public void uploadMedia() {}
}
piblic class FrontPage {
    private Post p = new Post();
    private final String subj = "OCA & OCP Prep Tools";
    public void compose(){ p.write(1200, 2); }
}
piblic class StickyPost extends Post {
    public void write(int numberOfWords, int numberOfPix) {}
    public void publish() {}
}

Which statement is true?

A. A compilation error occurs in WordPress.
B. A compilation error occurs in Post.
C. A compilation error occurs in FrontPage.
D. A compilation error occurs in StickyPost.
E. All classes compile successfully.

Stage 3 Problem 14 (view answer and explanation)

You want to create a singleton class by using the Singleton design pattern. Which two statements enforce the singleton nature of the design?

A. Make the class static.
B. Make the constructor private.
C. Override equals() and hashCode() methods of the java.lang.Object class.
D. Use a static reference to point to the single instance.
E. Implement the Serializable interface.

Stage 3 Problem 15 (view answer and explanation)

You have been asked to create a ResourceBundle which uses a properties file to localize an application. Which code example specifies valid keys of panet and satellite with values of Earth and Moon?

A. Earth
Moon
B. planetEarth
satelliteMoon
C. planet, Earth, satellite, Moon
D. planet = Earth
satellite = Moon

Stage 3 Problem 16 (view answer and explanation)

Given the code fragment:

class Hollywood{
    public static void main(String[] args) {
        String title = "MUMMY STRIKES BACK!";
        System.out.println("Title = " + title.replace("M", "P"));
    }
}

What is the result?

A. Title = MUMMY STRIKES BACK!
B. Title = PUPPY STRIKES BACK!
C. A compile time error is produced.
D. A runtime error is produced.
E. Title =
F. Title = PUMMY STRIKES BACK!

Stage 3 Problem 17 (view answer and explanation)

Given the code fragment:

UnaryOperator<Integer> unop = x -> x*2;             // line 1
List<Double> nums = Arrays.asList(10.0, 20.0);
nums.stream()
    .filter(x -> x > 15.0)
    .map(x -> unop.apply(x))                        // line 2
    .forEach(x -> System.out.print(x));

What is the result?

A. 40.0
B. 40
C. A compilation error occurs at line 1.
D. A compilation error occurs at line 2.

Stage 3 Problem 18 (view answer and explanation)

Given the code fragment:

List<String> ad = Arrays.asList(
    "See", "Java", "run.",
    "Run", "Java", "run.");
Predicate<String> test = x -> {
    int i = 0;
    boolean hit = x.contains("Java");
    System.out.print(i++ + " - ");
    return hit;
};
ad.stream()
  .filter(test)
  .findFirst()
  .ifPresent(System.out::print);

What is the result?

A. 0 – 0 – Java
B. 0 – 1 – Java
C. 0 – 0 – 0 – 0 – 0 – 0 – Java
D. 0 – 1 – 2 – 3 – 4 – 5 – 6 –
E. A compilation error occurs

Stage 3 Problem 19 (view answer and explanation)

Given the code fragment:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter your score: ");
    //line 1
}

Which code fragment, when inserted at line 1, enables the code to read the user’s score?

A. int score = Integer.parseInt(br.readLine());
B. int score = br.read();
C. int score = br.nextInt();
D. int score = Integer.parseInt(br.next());

Stage 3 Problem 20 (view answer and explanation)

Given:

class WhiteStarLiner implements Sinkable {
    public void sink() { }
}

abstract class Shipwreck extends WhiteStarLiner { }

class Britannic extends WhiteStarLiner {
    protected void sink(int numberOfMines) { }
}

class Titanic extends WhiteStarLiner implements Sinkable {
    public void hitIceberg() { }
}

interface Sinkable {
    public abstract void sink();
}

Which statement is true?

A. Shipwreck does not compile.
B. Britannic does not compile.
C. Titanic does not compile.
D. Sinkable does not compile.
E. All classes compile successfully.

Stage 3 Problem 21 (view answer and explanation)

Given the code fragment:

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(3, 4);
//line n1

Which code fragment, when inserted at line n1, prints 1 2 3 4?

A. Stream.of(list1, list2)
         .flatMap(x -> x.stream())
         .forEach(x -> System.out.print(x + " "));
B. Stream.of(list1, list2)
         .flatMap(x -> x.intStream())
         .forEach(x -> System.out.print(x + " "));
C. list1 .stream()
         .flatMap(list2.stream().flatMap(x -> x.stream())
         .forEach(x -> System.out.println(x + " "));
D. Stream.of(list1, list2)
         .flatMapToInt(x -> x.stream())
         .forEach(x -> System.out.print(x + " "));

Stage 3 Problem 22 (view answer and explanation)

Given the code fragment:

class GirlFriend implements Callable<String> {
    String str;
    public GirlFriend(String str) {this.str = str;}
    public String call() throws Exception {
        return str.concat(" Call her!");
    }
}

and

public static void main (String[] args) throws InterruptedException, ExecutionException {
    ExecutorService exec = Executors.newFixedThreadPool(3); //line n1
    Future fut = exec.submit(new GirlFriend("Call her!"));
    String str = fut.get().toString();
    System.out.println(str);
}

Which statement is true?

A. The program prints Call her! Call her! and terminates.
B. The program prints Call her! Call her! and does not terminate.
C. A compilation error occurs at line n1.
D. An ExecutionException is thrown at run time.

Stage 3 Problem 23 (view answer and explanation)

Given the structure of the EMPLOYEE table:

Employee (id INTEGER, name VARCHAR)

Given:

public class Test {
    static Connection newConn = null;
    public static Connection getDBConnection() throws SQLException {
        try (Connection conn = DriverManager.getConnection(URL, login, password)) {
            newConn = conn;
        }
        return newConn;
   }
    public static void main(String[] args) throws SQLException {
        getDBConnection();
        Statement stat = newConn.createStatement();
        stat.executeUpdate("INSERT INTO employee VALUES (2, 'Joe Random')");
    }
}

Assume that:

  • The required database driver is configured in the classpath.
  • The appropriate database accessible with the URL, login, and password exists.
  • The SQL query is valid.

What is the result?

A. The program executes successfully and the EMPLOYEE table is updated with one record.
B. The program executes successfully and the EMPLOYEE table is NOT updated with any record.
C. A SQLException is thrown as runtime.
D. A NullPointerException is thrown as runtime.

Stage 3 Problem 24 (view answer and explanation)

Given:

class MutualFund{
    int capital;
    String name;
    public MutualFund (int capital, String name) {
        this.capital = capital;
        this.name = name;
    }
    public String toString () {
        return capital + ":" + name;
    }
}

and this code fragment:

Set<MutualFund> funds = new TreeSet<>();
funds.add(new MutualFund (293, "Pimco"));
funds.add(new MutualFund (190, "Vanguard"));
System.out.println(funds);

What is the result?

A. 293 Pimco
190 Vanguard
B. 190 Vanguard
293 Pimco
C. A compilation error occurs
D. A ClassCastException is thrown at run time

Stage 3 Problem 25 (view answer and explanation)

Given the records from the Player table:

----------------
| id  |  name  |
----------------
| 11  |  Ted   |
----------------
| 12  |  John  |
----------------
| 13  |  Dick  |
----------------

and given the code fragment:

try {
    Connection conn = DriverManager.getConnection(URL, login, password);
    Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                          ResultSet.CONCUR_UPDATABLE);
    stat.execute("SELECT * FROM Player");
    ResultSet rs = st.getResultSet();
    while (rs.next()) {
        if (rs.getInt(1) == 12) {
            rs.updateString(2, "Matt");
        }
    }
    rs.absolute(2);
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
} catch (SQLException ex) {
    System.out.println("Exception is raised");
}

Assume that:

  • The required database driver is configured in the classpath.
  • The appropriate database accessible with the URL, login, and password exists.

What is the result?

A. The Player table is updated with the row: 112 Matt and the program prints: 112 John
B. The Player table is updated with the row: 112 John and the program prints: 112 Matt
C. The Player table is not updated and the program prints: 112 John
D. The program prints Exception is raised

Stage 3 Problem 26 (view answer and explanation)

Which action can be used to load a database driver by using JDBC3.0?

A. Add the driver class to the META-INF/services folder of the JAR file.
B. Include the JDBC driver class in a jdbc.properties file.
C. Use the java.lang.Class.forName method to load the driver class.
D. Use the DriverManager.getDriver method to load the driver class.

Stage 3 Problem 27 (view answer and explanation)

Which statement is true about java.time.Duration?

A. It tracks time zones.
B. It preserves daylight saving time.
C. It defines time-based values.
D. It defines date-based values.

Stage 3 Problem 28 (view answer and explanation)

For which two reasons should you use interfaces instead of abstract classes?

A. You expect that classes that implement your interfaces have many common methods or fields, or require access modifiers other than public.
B. You expect that unrelated classes would implement your interfaces.
C. You want to share code among several closely related classes.
D. You want to declare non-static on non-final fields.
E. You want to take advantage of multiple inheritance of type.

Stage 3 Problem 29 (view answer and explanation)

Which statement is true about the DriverManager class?

A. It returns an instance of Connection.
B. It executes SQL statements against the database.
C. It only queries metadata of the database.
D. It is written by different vendors for their specific database.

Stage 3 Problem 30 (view answer and explanation)

Given the code fragment:

LocalDate javaBirthday = LocalDate.of(1995, Month.MAY, 23);
LocalDate twentiethAnniversary = javaBirthday.plusYears(20);
twentiethAnniversary.plusDays(1);                             //line n1
System.out.println(twentiethAnniversary);

What is the result?

A. 2015-05-23
B. A DateTimeException is thrown
C. 2015-05-24
D. A compilation error occurs at line n1

Stage 3 Problem 31 (view answer and explanation)

Given the content of /res/GoVPN.properties:

option1=”SoftEther”

and given the code fragment:

Properties prop = new Properties();
FileInputStream fis = new FileInputStream("/res/GoVPN.properties");
prop.load(fis);
System.out.println(prop.getProperty("option1"));
System.out.println(prop.getProperty("option2", "Opera ver.46.0"));   //line n1
System.out.println(prop.getProperty("option3"));

What is the result?

A. SoftEther
Opera ver.46.0
followed by an Exception stack trace
B. SoftEther
followed by an Exception stack trace
C. SoftEther
Opera ver.46.0
null
D. A compilation error occurs at line n1

Stage 3 Problem 32 (view answer and explanation)

Given the code fragment:

List<String> graces = Arrays.asList("faith", "hope", "love");
Predicate<String> test = x -> {
    System.out.println("Still waiting...");
    return x.contains("love");
};
graces.stream()
      .filter(x -> x.length() >= 4)
      .allMatch(test);

What is the result?

A. Still waiting…
B. Still waiting…
Still waiting…
C. Still waiting…
Still waiting…
Still waiting…
D. A compilation error occurs.

Stage 3 Problem 33 (view answer and explanation)

Given:

public class Item {
    int id; int price;
    public Item (int id, int price) {
        this.id = id;
        this.price = price;
    }
    public String toString() { return id + " : " + price; }
}

and the code fragment:

List<Item> inventory = Arrays.asList(new Item(1, 10),
    new Item(2, 15),
    new Item(3, 20));
Item item = inventory.stream()
                     .reduce(new Item(4, 0), (x, y) -> {
                             x.price += y.price;
                             return new Item(x.id, y.price);});
inventory.add(item);
inventory.stream()
         .parallel()
         .reduce((x, y) -> x.price > y.price ? x : y)
         .ifPresent(System.out::println); 

What is the result?

A. 4 : 45
B. 4 : 0
C. 4 : 20
D. 1 : 10
2 : 15
3 : 20
4 : 45
E. The program prints nothing

Stage 3 Problem 34 (view answer and explanation)

Given:

Bread.java:

public class Bread {
    private String eat(String piece) { return "Consume " + piece; }
}

Pizza.java:

public class Pizza extends Bread {
    public String eat (String slice) { return "Enjoy " + slice; }
}

Test.java:

public class Test {
    public static void main (String[] args) {
        Bread b1 = new Bread();
        b1.eat("bread.");
        Bread b2 = new Pizza();
        b2.eat("Quattro Stagioni.");
    }
}

What is the result?

A. Consume bread.
Enjoy Quattro Stagioni.
B. Consume bread.
Consume Quattro Stagioni.
C. The Pizza.java file fails to compile.
D. The Test.java file fails to compile.

Stage 3 Problem 35 (view answer and explanation)

Given the code fragments:

class Sprinter implements Runnable {
    private static AtomicInteger place = new AtomicInteger(0);
    public void run() {
        int p = place.incrementAndGet();
        System.out.print(p + " ");
    }
}

and

Thread justin1 = new Thread(new Sprinter());
Thread christian2 = new Thread(new Sprinter());
Thread usain3 = new Thread(new Sprinter());
Thread[] sprint = {justin1, christian2, usain3};
for (int i = 0; i < 3; i++) {
    sprint[i].start();
}

Stage 3 Problem 36 (view answer and explanation)

Given the code fragment:

ZonedDateTime departed = ZonedDateTime.of(1991, 4, 1, 19, 0, 0, 0, ZoneId.of("UTC+3"));
ZonedDateTime arrived = ZonedDateTime.of(1991, 4, 2, 9, 0, 0, 0, ZoneId.of("UTC+9"));
long hrs = ChronoUnit.HOURS.between(departed, arrived);     //line n1
System.out.println("Flight time was " + hrs + " hours");

What is the result?

A. Flight time was 8 hours
B. Flight time was 9 hours
C. Flight time was 10 hours
D. An exception is thrown at line n1

Stage 3 Problem 37 (view answer and explanation)

Given:

interface Answerable {
    public void answer(String question);
}

Which two class definitions compile?

A. abstract class Test implements Answerable {
       public void write(String essay) { }
   }
B. abstract class Exam implements Answerable {
       public abstract void answer(String str) { }
       public void faint(Boolean bool) { }
   }
C. class Quiz implements Answerable {
       public void answer(Integer num) { }
   }
D. class BlindDate implements Answerable {
       public void answer(Integer age) { }
       public String grin(Integer numberOfMissingTeeth) { }
   }
E. class Interrogation implements Answerable {
       public void answer(String nameAndRank) { }
       public void answer(Integer serialNumber) { }
       public void refuse(String otherQuestions) { }
   }

Stage 3 Problem 38 (view answer and explanation)

Given the code fragments:

2. void earn() throws ArithmeticException, NumberFormatException, Exception {
3.     if (Math.random() < 0.1) throw new Exception ("C'mon! You can do better than that.");
4. }

and

14. try {
15.     earn( );
16. } catch(ArithmeticException | NumberFormatException | Exception e) {
17.     System.out.println (e.getMessage()); }
18. catch(Exception e) {
19.     System.out.println (e.getMessage()); }
20. }

Which modification enables the code to print Try again?

A. Comment the lines 18, 19 and 20.

B. Replace line 16 with:

  } catch (Exception | ArithmeticException | NumberFormatException e) {

C. Replace line 16 with:

  } catch (ArithmeticException | NumberFormatException e) {

D. Replace line 17 with:

  throw e;

Stage 3 Problem 39 (view answer and explanation)

Which statement is true about the single abstract method of the java.util.function.Function interface?

A. It accepts one argument and returns void.
B. It accepts one argument and returns boolean.
C. It accepts one argument and always produces a result of the same type as the argument.
D. It accepts an argument and produces a result of any data type.

Stage 3 Problem 40 (view answer and explanation)

Given the code fragment:

public static void main (String[] args) throws IOException {
    BufferedReader brCopy = null;
    try (BufferedReader br = new BufferedReader(new FileReader("derby.log"))) { //line n1
        br.lines().forEach(x -> System.out.println(x));
        brCopy = br;     //line n2
    }
    brCopy.ready();      //line n3;
}

Assume that the ready method of the BufferedReader, when called on a closed BufferedReader, throws an exception, and derby.log is accessible and contains valid text. What is the result?

A. A compilation error occurs at line n3.
B. A compilation error occurs at line n1.
C. A compilation error occurs at line n2.
D. The code prints the content of the derby.log file and throws an exception at line n3.

Stage 3 Problem 41 (view answer and explanation)

Given:

1. abstract class Comsat {
2. Comsat( ) { System.out.println ("Communication Satellite"); }
3. protected void transmit( ) { System.out.println ("Communication Satellite"); }
4. }
5.
6. class Constellation extends Comsat {
7. int num;
8. Constellation(int num) {
9.  /* insert code here */
10. this.num = num;
11. }
12.  public void transmit( ) { System.out.println ("Constellation of comsats"); }
13. }
14. class Galileo extends Constellation {
15. int height, incl;
16. Galileo(int x, int y) {
17. /* insert code here */
18. height = x; incl = y;
19. }
20. void transmit( ) { System.out.println ("Galileo"); }
21.}

Which two modifications enable the code to compile?

A. At line 1, remove abstract
B. At line 9, insert super ( );
C. At line 12, remove public
D. At line 17, insert super(x);
E. At line 17, insert super(); super.num = x;
F. At line 20, use public void transmit( ) {

Stage 3 Problem 42 (view answer and explanation)

Given:

class Browser {
    public void surf() {
        System.out.print("See me surf!");
    }
}
class Tor extends Browser {
    public void surf() {
        System.out.print("Stealth mode engaged.");
    }
}

and the code fragment:

class Tails {
    public static void main(String[] args) {
        surf(() -> new Browser());
        surf(Tor::new);
    }
    /* line n1 */
}

Which code fragment, when inserted at line n1, enables the Tails class to compile?

A. static void surf(Consumer<Browser> browser) { browser::surf(); }
B. static void surf(Consumer<? extends Browser> browser) { browser.accept().surf(); }
C. static void surf(Supplier<Browser> browser) { browser.get().surf(); }
D. static void surf(Supplier<? extends Browser> browser) { browser::surf(); }

Stage 3 Problem 43 (view answer and explanation)

Given:

class Band {
    String name, style, country;
    public Band (String name, String style, String country) {
        this.style = style;
        this.name = name;
        this.country = country;
    }
    public String getStyle() {
        return style;
    }
    public String toString() {
        return style + " : " + name + " : " + country;
    }
}

and the code fragment:

List<Band> bands = Arrays.asList(
    new Band("Yes", "Prog Rock", "UK"),
    new Band("Boney M", "Euro Disco", "Germany"),
    new Band("ELP", "Prog Rock", "UK"));
bands.stream()
     .collect(Collectors.groupingBy(Band::getStyle))
     .forEach( (x, y) -> System.out.println(x) );

What is the result?

A. [Euro Disco : Boney M : Germany]
[Prog Rock : Yes : UK, Prog Rock : ELP : UK]
B. Euro Disco
Prog Rock
C. [Prog Rock : Yes : UK, Prog Rock : ELP : UK]
[Euro Disco : Boney M : Germany]
D. A compilation error occurs

Stage 3 Problem 44 (view answer and explanation)

Given:

class Jerry extends Thread {
    CyclicBarrier cb;
    public Jerry(CyclicBarrier cb) { this.cb = cb; }
    public void run() {
        try {
        cb.await();
        System.out.println("Jerry running");
        } catch (Exception ex) { }
    }
}

class Tom implements Runnable { //line n1
    public void run() {
        System.out.println("Tom chasing");
    }
}

and the code fragment:

Tom tom = new Tom();
//line n2
Jerry jerry = new Jerry(cb);
jerry.start();

You have been asked to ensure that the run methods of both the Tom and Jerry classes are executed. Which modification meets the requirement?

A. At line n2, insert CyclicBarrier cb = new CyclicBarrier(2, tom);
B. Replace line n1 with class Master extends Thread {
C. At line n2, insert CyclicBarrier cb = new CyclicBarrier(1, tom);
D. At line n2, insert CyclicBarrier cb = new CyclicBarrier(tom);

Stage 3 Problem 45 (view answer and explanation)

Given the code fragment:

public class MapPetShow {
    public static void main (String [ ] args) {

        Map<Integer, String> sourceMap = new HashMap<>( );
        sourceMap.put(37, "Ms.Piggy ");
        sourceMap.put(8, "Gonzo ");
        sourceMap.put(4, "Rowlf ");
        sourceMap.put(12, "Fozzie ");
        sourceMap.put(82, "Kermit ");

        Map<Integer, String> finalMap = new TreeMap<Integer, String> (
            new Comparator<Integer> ( ) {
                @Override
                public int compare(Integer obj1, Integer obj2) {
                    return obj2.compareTo(obj1);
        }});

        finalMap.putAll(sourceMap);
        for (Map.Entry<Integer, String> entry : finalMap.entrySet()) {
            System.out.print(entry.getValue());
        }
    }
}

What is the result?

A. A compilation error occurs
B. Rowlf Gonzo Fozzie Ms.Piggy Kermit
C. Kermit Ms.Piggy Fozzie Gonzo Rowlf
D. Rowlf Ms.Piggy Kermit Fozzie Gonzo

Stage 3 Problem 46 (view answer and explanation)

Given the code fragments:

class Customer {
    Optional<Email> contact;
    Customer (Optional<Email> contact) {
        this.contact = contact;
    }
    public Optional<Email> getContact() {
        return contact;
    }
}
class Email {
    String email = "joe.random@planet.earth";
    public String getEmail() { return email; }
    public String toString() {
        return email;
    }
}

and

Email email = null;
Optional<Email> contact = Optional.ofNullable(email);
Customer cust = new Customer(contact);
String eEmail = (contact.isPresent()) ? contact.get().getEmail() : "N/A";
System.out.println(eEmail);

What is the result?

A. joe.random@planet.earth
B. N/A
C. null
D. A NoSuchElementException is thrown at run time

Stage 3 Problem 47 (view answer and explanation)

Given:

class Catcher{
    static void calculate(int[] num){
        try{
            System.out.println(num[1] / (num[1] - num[2]));
        } catch(ArithmeticException ae){
            System.err.println("First one caught");
        }
    }
    public static void main(String[] args){
        try{
            int[] arr = {100, 100};
            calculate(arr);
        } catch(IllegalArgumentException iae){
            System.err.println("Second one caught");
        } catch(Exception e){
            System.err.println("Third one caught");
        }
    }
}

What is the result?

A. 0 Done
B. First one caught
Done
C. Second one caught
D. Done
Third one caught
E. Third one caught

Stage 3 Problem 48 (view answer and explanation)

Given the code fragment:

public void erase(String dirName) throws IOException {
    File[] listOfFiles = new File(dirName).listFiles();
    if ( listOfFiles != null && listOfFiles.length > 0 ) {
        for (File aFile : listOfFiles) {
            if (aFile.isDirectory()) {
                erase(aFile.getAbsolutePath());
          } else {
                if (aFile.getName().endsWith(".txt"))
                    aFile.delete();
            }
        }
    }
}

Assume that the MyProg directory contains subdirectories that contain .txt files and is passed as an argument to the recDelete() method when it is invoked.

What is the result?

A. The method deletes all the .txt files in the MyProg directory and its subdirectories.
B. The method deletes the .txt files of the MyProg directory only.
C. The method executes and does not make any changes to the MyProg directory.
D. The method throws an IOException.

Stage 3 Problem 49 (view answer and explanation)

Given the code fragment:

List<String> listVal = Arrays.asList("Joe", "Paul", "Alice", "Tom");
System.out.println (
// line n1
);

Which code fragment, when inserted at line n1, enables the code to print the count of string elements whose length is greater than three?

A. listVal.stream().filter(x -> x.length()>3).count()
B. listVal.stream().map(x -> x.length()>3).count()
C. listVal.stream().peek(x -> x.length()>3).count().get()
D. listVal.stream().filter(x -> x.length()>3).mapToInt(x -> x).count()

Stage 3 Problem 50 (view answer and explanation)

Which statement is true about java.util.stream.Stream?

A. A stream cannot be consumed more than once.
B. The execution mode of streams can be changed during processing.
C. Streams are intended to modify the source data.
D. A parallel stream is always faster than an equivalent sequential stream.

Stage 3 Problem 51 (view answer and explanation)

Given the code fragment:

String str = "Say what?!";
ToIntFunction<String> indx = str::indexOf;   //line n1
int a = indx.applyAsInt("Say");              //line n2
System.out.println(a);

What is the result?

A. 0
B. 1
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2

Stage 3 Problem 52 (view answer and explanation)

Given the code fragment:

Path file = Paths.get("passwords.txt");
// line n1

Assume the passwords.txt is accessible. Which code fragment can be inserted at line n1 to enable the code to print the content of the passwords.txt file?

A. List<String> fc = Files.list(file);
   fc.stream().forEach(x -> System.out.println(x));
B. Stream<String> fc = Files.readAllLines(file);
   fc.forEach(x -> System.out.println(x));
C. List<String> fc = readAllLines(file);
   fc.stream().forEach(x -> System.out.println(x));
D. Stream<String> fc = Files.lines(file);
   fc.forEach(x -> System.out.println(x));

Stage 3 Problem 53 (view answer and explanation)

Given:

public enum Season {
    WINTER (6),
    SPRING(10),
    SUMMER (25),
    FALL(14);
    private int averageTemp;
    public Season(int averageTemp) {
        this.averageTemp = averageTemp;
    }
    public int getTemp() {return averageTemp;}
}
public class Vacationer {
    public static void main (String[] args) {
        Season ssn = new Season.SUMMER;
        System.out.println(ssn.getTemp());
    }
}

Which two modifications enable the given code to compile?

A. Nest the Season enumeration declaration within the Vacationer class.
B. Make the Season enumeration constructor private.
C. Remove the new keyword from the instantion of ssn.
D. Make the getter method of averageTemp as a static method.
E. Add the final keyword in the declaration of averageTemp.

Stage 3 Problem 54 (view answer and explanation)

Given:

class Sum extends RecursiveAction {               //line n1

    static final int THRESHOLD = 3;
    int start, end;
    int[] val;

    public Sum(int[] val, int start, int end) {
        this.val = val;
        this.start = start;
        this.end = end;
    }

    protected void compute() {
        int sum = 0;
        if (end - start <= THRESHOLD) {
            for (int i = start; i < end; i++) {
                sum += val[i];
            }
            System.out.println(sum);
        } else {
            new Sum(val, start + THRESHOLD, end).fork();
            new Sum(val, start,
                    Math.min(end, start + THRESHOLD)
            ).compute();
        }
    }
}

and the code fragment:

ForkJoinPool fjp = new ForkJoinPool();
int val[] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
fjp.invoke(new Sum(val, 0, val.length));

and given that the sum of all integers from 11 to 20 is 155.

Which statement is true?

A. The program prints several values that total 155.
B. The program prints 155.
C. A compilation error occurs at line n1.
D. The program prints several values whose sum exceeds 155.

Stage 3 Problem 55 (view answer and explanation)

Given the code format:

class AccessKey{
    String user;
    String pass;
}

and

12. class DBAccess{
13.    AccessKey grantAccess(String user, String pass){
14.    // insert code here
15.    }
16.    public static void main(String[] args){
17.        DBAccess dba = new DBAccess();
18.        AccessKey key = dba.grantAccess("Bill", "1234");
19.    }
20. }

Which code fragment must be inserted at line 14 to enable the code to compile?

A. AccessKey x; return x;
B. return AccessKey;
C. return new AccessKey();
D. return 0;

Stage 3 Problem 56 (view answer and explanation)

Given the definition of the ExamTaker class:

public class ExamTaker {
    private String name;
    private Integer score;
    ExamTaker(String name, Integer score) {
        this.name = name;
        this.score = score;
    }
    public String getName() {return name;}
    public Integer getScore() {return score;}
}

and code fragment:

List<ExamTaker> list = Arrays.asList(
    new ExamTaker("Alice", 98),
    new ExamTaker("Bob", 64),
    new ExamTaker("Chris", 72));
Predicate<ExamTaker> passed = e -> e.getScore() >= 65;              //line n1
list = list.stream().filter(passed).collect(Collectors.toList());
Stream<String> names = list.stream().map(ExamTaker::getName);       //line n2
names.forEach(x -> System.out.print(x + " "));

What is the result?

A. Alice Bob Chris
B. Alice Chris
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2

Stage 3 Problem 57 (view answer and explanation)

Given the code fragment:

Path path1 = Paths.get("/app/./sys/");
Path res1 = path1.resolve("log");
Path path2 = Paths.get("/server/exe/");
Path res2 = path2.resolve("/readme/");
System.out.println(res1);
System.out.println(res2);

Path p1 = Paths.get("/usr/./bin/");
Path r1 = p1.resolve("python");
Path p2 = Paths.get("/var/lib/");
Path r2 = p2.resolve("/home/");
System.out.println(r1);
System.out.println(r2);

What is the result?

A. /usr/bin/python
/home/var/lib
B. /usr/python/bin
/var/lib/home
C. /usr/./bin/python
/home
D. /usr/./bin/python
/var/lib/home

Stage 3 Problem 58 (view answer and explanation)

Given:

public class B implements A {
    public String toString() {
        return "B ";
    }
    public static void main(String[] args) {
        C myC = new C();
        B myB = myC;
        A myA = myB;
        System.out.print(myB);
        System.out.print((C) myB);
        System.out.print(myA);
    }
}
class C extends B {
    public String toString() {
        return "C ";
    }
}
interface A {
    public String toString();
}

What is the result?

A. B B B
B. B C B
C. C C B
D. C C C
E. The code throws a ClassCastException

Stage 3 Problem 59 (view answer and explanation)

Given:

class NoNameException extends Exception{}
class YearOutOfRangeException extends Exception{}
class Company{
    String name;
    int est;
    Company(String name, int est) throws Exception {
        if(name == null) {
            throw new NoNameException();
        }else if(est <= 0 || est >= 2100) {
            throw new YearOutOfRangeException();
        }else{
            this.name = name;
            this.est = est;
        }
    }
    public String toString(){
        return name + " was founded in " + est;
    }
}

And given the code fragment:

26. class Test{
27.     public static void main(String[] args) {
28.         Company comp1 = new Company("Google", 1998);
29.         Company comp2 = new Company("Microsoft", 1975);
30.         System.out.println(comp1);
31.         System.out.println(comp2);
32.     }
33. }

Which change enables the code to print the following?

Google was founded in 1998
Microsoft was founded in 1975

A. Replacing line 27 with

    public static void main (String [] args) throws NoNameException, YearOutOfRangeException {

B. Replacing line 27 with

    public static void main (String [] args) throws Exception {

C. Enclosing line 28 and line 29 within a try block and adding:

    catch (Exception e) { /* code goes here */ }
    catch (NoNameException nne) { /* code goes here */ }
    catch (YearOutOfRangeException yoore) { /* code goes here */ }

D. Enclosing line 28 and line 29 within a try block and adding:

    catch (NoNameException nne) { /* code goes here */ }
    catch (YearOutOfRangeException yoore) { /* code goes here */ }

Stage 3 Problem 60 (view answer and explanation)

Given:

class A {
    public void runA() {
        System.out.println("ArunA");
    }
}

class B extends A {
    public void runA() {
        System.out.println("BrunA");
    }
    public void runB() {
        System.out.println("BrunB");
    }
}

public class Test {
    public static void main(String[] args) {
        A a = new B();
        B b = (B)a;
        b.runB();
        a.runA();
    }
}

What is the result?

A. BrunB
ArunA
B. BrunB
BrunA
C. Compilation fails
D. A ClassCastException is thrown at runtime

Stage 3 Problem 61 (view answer and explanation)

Given:

class DataEncryptedException extends Exception {}
class Computer {
    void crunch() throws DataEncryptedException {  // line n1
        System.out.println("Yummy!");
    }
}
class Supercluster extends Computer {
    public void crunch() throws Exception {        // line n2
        super.crunch();
    }
}

and the code fragment:

public static void main(String[] args) throws DataEncryptedException, Exception {
    Computer c = new Supercluster();
    c.crunch();
}

Which modification enables the code fragment to print Yummy!?

A. Replace line n1 with

    public void crunch() throws DataEncryptedException {

B. Replace line n1 with

    protected void crunch() throws Exception {

C. Replace line n2 with

    void crunch() throws Exception {

D. Replace line n2 with

    private void crunch() throws DataEncryptedException {

Stage 3 Problem 62 (view answer and explanation)

Given the code fragment:

int b = 3;
if ( !(b > 3) ) {
    System.out.println("square ");
}{
    System.out.println("circle ");
}
System.out.println("...");

What is the result?

A. square

B. circle

C. square
circle

D. Compilation fails

Stage 3 Problem 63 (view answer and explanation)

Given the code fragments:

interface Surveillable {}

class Target implements Surveillable {}

class PrimeSuspect extends Target {}

class Mission {
    public static void main(String[] args) {
        List objectives = new ArrayList();
        Surveillable s1 = new Target();
        Surveillable s2 = new PrimeSuspect();        // line n1
        Target t1 = new PrimeSuspect();

        objectives.add(s1);
        objectives.add(s2);
        objectives.add(t1);                          // line n2

        for (Object item : objectives) {
            System.out.println(item.getClass().getName());
        }
    }
}

What is the result?

A. Target
PrimeSuspect
PrimeSuspect
B. Surveillable
Surveillable
Target
C. Compilation fails at line n1
D. Compilation fails at line n2

Stage 3 Problem 64 (view answer and explanation)

Given the code fragment:

Path src = Paths.get("/home/pi/.bashrc_history");
Path dest = Paths.get("/home");
Files.copy(src, dest);

and assuming that the file /home/pi/.bashrc_history is accessible and contains:

whoami

What is the result?

A. A file with the name .bashrc_history is created in the /home directory and the content of the /home/pi/.bashrc_history file is copied to it.
B. The program executes successfully and does NOT change the file system.
C. A FileNotFoundException is thrown at run time.
D. A FileAlreadyExistsException is thrown at run time.

Stage 3 Problem 65 (view answer and explanation)

Given:

class CommCodes {
    public static int checkLength(String str1, String str2) {
        return str2.length() - str1.length();
    }
}

class Test{
    public static void main(String[] args) {
        String[] strArr = new String[]{"Sitrep", "Over", "Out", "Roger"};

        //line n1

        for (String s : strArr) {
            System.out.print(s + " ");
        }
    }
}

Which code fragment should be inserted at line n1 to enable the code to print Sitrep Roger Over Out?

A. Arrays.sort(strArr, CommCodes :: checkLength);
B. Arrays.sort(strArr, (new CommCodes()) :: checkLength);
C. Arrays.sort(strArr, (CommCodes :: new).checkLength);
D. Arrays.sort(strArr, CommCodes :: new :: checkLength);

Stage 3 Problem 66 (view answer and explanation)

Given the code fragment:

Map<Integer, String> students = new TreeMap<>();
students.put (17, "Alice");
students.put (12, "Chuck");
students.put (11, "Brian");
students.put (13, "Bob");
System.out.println (students);

What is the result?

A. {17 = Alice, 12 = Chuck, 11 = Brian, 13 = Bob}
B. {11 = Brian, 12 = Chuck, 13 = Bob, 17 = Alice}
C. {12 = Chuck, 13 = Bob, 17 = Alice}
D. {17 = Alice, 11 = Brian, 13 = Bob, 12 = Chuck}

Stage 3 Problem 67 (view answer and explanation)

Given the code fragment:

public class Test {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        for ( missing_code ) {
        }
    }
}

Which three are valid replacements for missing_code so that the program will compile and run?

A. int i : array
B. int i = 0; i < 1; i++
C. ;;
D. ; i < 1; i++
E. ; i < 1;

Stage 3 Problem 68 (view answer and explanation)

Given the definition of the following class:

class LongDistanceVoIP {
    double tariff;
    LongDistanceVoIP(double tariff) {
        this.tariff = tariff;
    }
    public void makeCall(int time) {
        int minutes = time;
        class CallingChicago {                              // line n1
            double charge = 0;
            public void calcCost() {
                charge = minutes * tariff;                  // line n2
                System.out.println("It'll set me back for " + charge + " cents.");
            }
        }
        new CallingChicago().calcCost();                    // line n3
    }
}

and this code fragment:

LongDistanceVoIP ld = new LongDistanceVoIP(1.1);
ld.makeCall(10);

What is the result?

A. It’ll set me back for 11.0 cents.
B. A compilation error occurs at line n1.
C. A compilation error occurs at line n2.
D. A compilation error occurs at line n3.

Stage 3 Problem 69 (view answer and explanation)

Given:

class Puzzler {

    int tally = 0;

    public void doStuff(int val) {
        if (val % 2 == 0) {
            break;
        } else {
            for (int i = 0; i < val; i++) {
                tally += i;
            }
        }
    }

    public static void main(String[] args) {
        Puzzler obj = new Puzzler();
        System.out.println("Left " + obj.tally);
        obj.doStuff(4);
        System.out.println("Middle " + obj.tally);
        obj.doStuff(5);
        System.out.println("Right " + obj.tally);
    }
}

What is the result?

A. Left 0
Middle 0
Right 5
B. Left 0
Middle 0
Right 10
C. Left 0
Middle 3
D. Right 6
E. Compilation fails

Stage 3 Problem 70 (view answer and explanation)

Given the code fragments:

interface Klondike extends Predicate<String> {
    public default boolean test(String str) {
        return str.equals("Gold");
    }
}

and

List<String> list = Arrays.asList("Gold Rush", "Gold Flakes", "Gold Nuggets");
Predicate<String> mesh1 = x -> x.length() > 3;
Predicate mesh2 = new Klondike() {           //line n1
    public boolean test(String str) {
        return str.contains("Gold");
    }
};
long num = list.stream()
        .filter(mesh1)
        .filter(mesh2)                        //line n2
        .count();
System.out.println(num);

What is the result?

A. 1
B. 3
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2

Stage 3 Problem 71 (view answer and explanation)

Given:

class Gadget {
    int id;
    String name;
    public Gadget(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public boolean equals(Object obj) {      // line n1
        boolean result = false;
        Gadget b = (Gadget) obj;
        if (this.name.equals(b.name)) {
            result = true;
        }
        return result;
    }
}

and the code fragment:

Gadget g1 = new Gadget(01, "iPhone");
Gadget g2 = new Gadget(10, "iPhone");
System.out.println(g1.equals(g2));           // line n2

Which statement is true?

A. The program prints true.
B. The program prints false.
C. A compilation error occurs. To ensure successful compilation, replace line n1 with:
    boolean equals (Gadget obj) {
D. A compilation error occurs. To ensure successful compilation, replace line n2 with:
    System.out.println(g1.equals((Object) g2));

Stage 3 Problem 72 (view answer and explanation)

The log.err, log.txt and log.dat files are accessible and contain text.

Given the code fragment:

Stream<Path> paths = Stream.of(Paths.get("log.err"),
        Paths.get("log.txt"),
        Paths.get("log.dat"));
paths.filter(x -> x.toString().endsWith("err")).forEach(
        x -> {
            try {
                Files.readAllLines(x)
                    .stream()
                     .forEach(System.out::println);       // line n1
            } catch (IOException ioe) {
                System.out.println("Exception raised!");
            }
        });

What is the result?

A. The program prints the content of the log.err file.
B. The program prints:
Exception raised!
<The content of the log.err file>
Exception raised!
C. A compilation error occurs at line n1.
D. The program prints the content of the three files.

Stage 3 Problem 73 (view answer and explanation)

Given the code fragment:

Stream<List<String>> listStream = Stream.of(
        Arrays.asList("1", "Smith"),
        Arrays.asList("2", null));
IntStream intStream = listStream.flatMapToInt((x) -> x.stream());
intStream.forEach(System.out::print);

What is the result?

A. 1Smith2null
B. 12
C. A NullPointerException is thrown at run time
D. A compilation error occurs

Stage 3 Problem 74 (view answer and explanation)

Given the code fragment:

Stream<Path> files = Files.walk(Paths.get(System.getProperty("user.home")));
files.forEach(fName -> {                       // line n1
    try {
        Path aPath = fName.toAbsolutePath();   // line n2
        System.out.println(fName + ":"
                + Files.readAttributes(aPath, BasicFileAttributes.class).creationTime());
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
});

What is the result?

A. All files and directories under the home directory are listed along with their attributes.
B. A compilation error occurs at line n1.
C. The files in the home directory are listed along with their attributes.
D. A compilation error occurs at line n2.

Stage 3 Problem 75 (view answer and explanation)

Given the code fragment:

16. Connection conn = DriverManager.getConnection(db, login, psw);
17. String query = "SELECT id FROM Product";
18. try (Statement stat = conn.createStatement()) {
19.     ResultSet rs = stat.executeQuery(query);
20.     stat.executeQuery("SELECT id FROM Manufacturer");
21.     while (rs.next()) {
22.         // process the results
23.         System.out.println("Product ID: " + rs.getInt("id"));
24.     }
25. } catch (Exception e) {
26.     System.out.println("Error");
27. }

Assume that:

  • The required database driver is configured in the classpath.
  • The appropriate database accessible with the db, login, and psw exists.
  • The Product and Manufacturer tables are available and each table has id column with a few records and the SQL queries are valid.

What is the result of compiling and executing this code fragment?

A. The program prints Product IDs.
B. The program prints Manufacturer IDs.
C. The program prints Error.
D. Compilation fails on line 20.

Stage 3 Problem 76 (view answer and explanation)

Given the code fragment:

List<String> names = Arrays.asList("Alice", "Bob", "Chuck");
Function<String, String> func = x -> "Hi ".concat(x);
names.stream()
     .map(func)
     .peek(System.out::println);

What is the result?

A. Hi Alice
Hi Bob
Hi Chuck
B. Alice
Bob
Chuck
C. The program prints nothing
D. A compilation error occurs

Stage 3 Problem 77 (view answer and explanation)

Given the code fragment:

Path pa = Paths.get("/home/user.dat");
System.out.println(pa.getNameCount()
        + " - " + pa.getName(1)
        + " - " + pa.getFileName());

Assume that the home directory does NOT exist. What is the result?

A. An exception is thrown at run time
B. 2 – user.dat – user.dat
C. 1 – home – /home/user.dat
D. 2 – home – user.dat

Stage 3 Problem 78 (view answer and explanation)

Given the code fragment:

List<String> planets = Arrays.asList("Mercury, 0",
        "Venus, 0",
        "Earth, 1",
        "Mars, 2");
planets.stream()
       .filter(x -> x.contains("M"))
       .sorted()
       .forEach(System.out::println);    //line n1

What is the result?

A. Mars, 2
Mercury, 0
B. A compilation error occurs at line n1
C. Mercury, 0
Venus, 0
Earth, 1
Mars, 2
D. Earth, 0
Venus, 0

Stage 3 Problem 79 (view answer and explanation)

Given:

public class Test{
    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int z = y += x/5;
        System.out.print(x + " : " + y + " : " + z);
    }
}

What is the result?

A. 10 : 22 : 20
B. 10 : 22 : 22
C. 10 : 22 : 6
D. 10 : 30 : 6

Stage 3 Problem 80 (view answer and explanation)

Given:

class Blogging {
    public static void main (String[] args) {
        int followers = 0;
        String subject = "Programming Languages";
        switch (subject) {
            case "Java": followers = 3;
                break;
            case "Nairi": followers = 0;
                break;
            default:
                assert false: "Start another blog";        // line n1
        }
        System.out.println ("Currently " + followers + " followers");
    }
}

and the command:

java -ea Blogging

What is the result?

A. Currently 0 followers
B. An AssertionError is thrown
C. Start another blog
D. A compilation error occurs at line n1

Stage 3 Problem 81 (view answer and explanation)

Given:

public class Apollo11 {
    public static void main(String[] args) {
        String crew[] = new String[3];
        crew[0] = "Neil Armstrong";
        crew[1] = "Buzz Aldrin";
        crew[2] = "Mike Collins";
        try {
            for (String n : crew) {
                try {
                    String scrambled = n.substring(0, 3) + n.substring(8, 12);
                    System.out.println(scrambled);
                } catch (StringIndexOutOfBoundsException sioobe) {
                    System.out.println("String out of limits");
                }
            }
        } catch (ArrayIndexOutOfBoundsException aioobe) {
            System.out.println("Array out of limits");
        }
    }
}

What is the result?

A. Neistro
String out of limits
Miklins
B. Neistro
String out of limits
Array out of limits
C. Neistro
String out of limits
D. Neistro
Buzrin
Miklins

Stage 3 Problem 82 (view answer and explanation)

Given:

public class Record<K, V> {
    private K key;
    private V value;
    public Record(K key, V value) {
        this.key = key;
        this.value = value;
    }
    public static <T> Record<T, T> write(T value) {
        return new Record<T, T>(value, value); }
    public K getKey() {return key;}
    public V getVal() {return value;}
}

Which option fails?

A. Record<String, Integer> employee = new Record<String, Integer> (“Smith”, 25);
B. Record<String, String> quote = Record.<String> write(“Knowledge is power.”);
C. Record<Object, Object> score = new Record<String, Integer> (“Joe Random”, 86);
D. Record<String, String> animation = new Record<> (“Shaun The Sheep”, “Season 5”);

Stage 3 Problem 83 (view answer and explanation)

Given:

Item Table

ID, INTEGER: PK
DESCRIP, VARCHAR(100)
PRICE, REAL
QUANTITY, INTEGER

And given the code fragment:

 9. try {
10.     Connection conn = DriverManager.getConnection(db, login, password);
11.     String query = "Select * FROM Item WHERE ID = 11";
12.     Statement stat = conn.createStatement();
13.     ResultSet rs = stmt.executeQuery(query);
14.     while (rs.next()) {
15.         System.out.println("ID:" + rs.getInt("Id"));
16.         System.out.println("Description:" + rs.getString("Descrip"));
17.         System.out.println("Price:" + rs.getDouble("Price"));
18.         System.out.println("Quantity:" + rs.getInt("Quantity"));
19.     }
20. } catch (SQLException se) {
21.     System.out.println("Error");
22. }

Assume that:

  • The required database driver is configured in the classpath.
  • The appropriate database accessible with the db, login, and password exists.
  • The SQL query is valid.

What is the result?

A. An exception is thrown at runtime.
B. Compilation fails.
C. The code prints Error.
D. The code prints information about Item 11.

Stage 3 Problem 84 (view answer and explanation)

Given the definition of the Coder class:

public class Coder {
    enum Gender {
     FEMALE, MALE,
    }
    String name;
    Gender gender;
    public Coder(String name, Gender gender) {
        this.name = name;
        this.gender = gender;
    }
    public String getName() {
        return name;
    }
    public Gender getGender() {
        return gender;
    }
}

and the code fragment:

List<Coder> list = Arrays.asList(
        new Coder("Alice", Coder.Gender.FEMALE),
        new Coder("Chuck", Coder.Gender.MALE),
        new Coder("Bob", Coder.Gender.MALE));
Map<Coder.Gender, List<String>> classification = list.stream().
        collect(Collectors.groupingBy(Coder::getGender,
                Collectors.mapping(Coder::getName, Collectors.toList())));
System.out.println(classification);

What is the output?

A. {MALE = [Chuck, Bob], FEMALE = [Alice]}
B. {FEMALE = [Alice], MALE = [Chuck, Bob]}
C. {MALE = [Bob, Chuck], FEMALE = [Alice]}
D. {MALE = [Bob], MALE = [Chuck], FEMALE = [Alice]}

Stage 3 Problem 85 (view answer and explanation)

Given:

class NameException extends Exception { }
class ScoreOutOfLimitException extends NameException { }

and the code fragment:

class Test {
    public void check(String name, int age) throws NameException, ScoreOutOfLimitException {
        if (name.length() < 4) {
            throw new NameException();
        } else if (age >= 65) {
            throw new ScoreOutOfLimitException();
        } else {
            System.out.println("Passed.");
        }
    }
    public static void main(String[] args) throws NameException {
        Test t = new Test();
        t.check("John", 65);
    }
}

What is the result?

A. Passed.
B. An ScoreOutOfLimitException is thrown.
C. A NameException is thrown.
D. A compilation error occurs in the main method.

Stage 3 Problem 86 (view answer and explanation)

Given:

class Bid implements AutoCloseable {
    public void close() throws Exception {
        System.out.print("Bid closed. ");
   }
    public void placeBid() throws Exception {
        System.out.print("Placing bid. ");
        throw new Exception("Unable to place bid. ");
    }
}
class Auction implements AutoCloseable {
    public void close() throws Exception {
        System.out.print("Auction closed. ");
    }
    public void acceptBid() {
        System.out.print("Bid accepted.");
    }
}

and this code fragment:

try(Bid bid = new Bid();
    Auction auc = new Auction()) {
    bid.placeBid();
    auc.acceptBid();
} catch (Exception e) {
    System.out.print(e.getMessage());
}

What is the result?

A. Placing bid. Auction closed. Bid closed. Unable to place bid.
B. Placing bid. Bid closed. Unable to place bid.
C. Placing bid. Unable to place bid.
D. Placing bid. Unable to place bid. Auction closed.

Stage 3 Problem 87 (view answer and explanation)

Given the code fragment:

List<Integer> list = Arrays.asList(13, 6, 62);
System.out.println(
        //line n1
    );

Which code fragment must be inserted at line n1 to enable the code to print the minimum number in the list object?

A. list.stream().min(Comparator.comparing(x -> x)).get()
B. list.stream().min(Integer::min).get()
C. list.stream().min()
D. list.stream().map(x -> x).min()

Stage 3 Problem 88 (view answer and explanation)

Given that test.txt is accessible and contains:

Math::max

and given the code fragment:

public static void main(String[] args){
    int i;
    char c;
    try(FileInputStream fis = new FileInputStream("test.txt");
        InputStreamReader isr = new InputStreamReader(fis);) {
        while (isr.ready()) { //line n1
            isr.skip(2);
            i = isr.read();
            c = (char) i;
            System.out.print(c);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

What is the result?

A. thma
B. t:x
C. The program prints nothing.
D. A compilation error occurs at line n1.

Stage 3 Problem 89 (view answer and explanation)

Given:

public class Division {
    public static void main(String[] args) {
        int x = 10;
        int y = -1;
        assert (y >= 1) : "Wrong divisor";
        int z = x / y;
        System.out.println(z);
    }
}

What is the result of running the code with the ‚Äďea option?

A. -10
B. 0
C. An AssertionError is thrown.
D. A compilation error occurs.

Stage 3 Problem 90 (view answer and explanation)

Given:

public class Test<T> {
    private T t;
    public T getT() {
        return t;
    }
    public void setT(T t) {
        this.t = t;
    }
    public static void main(String args[]) {
        Test<String> obj1 = new Test<>();
        Test obj2 = new Test();                 // line n1
        obj1.setT("1Z0");
        obj2.setT(809);                         // line n2
        System.out.print(obj1.getT() + "-" + obj2.getT());
    }
}

What is the result?

A. 1Z0-809
B. java.lang.String@<hashcode>
java.lang.Integer@<hashcode>
C. A compilation error occurs. To rectify it, replace line n1 with:
Test<Integer> obj2 = new Test<>();
D. A compilation error occurs. To rectify it, replace line n2 with:
obj2.setT(Integer(809));

Stage 3 Problem 91 (view answer and explanation)

Given:

IntStream inStr = IntStream.of(1, 2, 3);
IntFunction<Integer> inFunc = x -> y -> x * y;     // line n1
IntStream result = inStr.map(inFunc.apply(4));     // line n2
result.forEach(System.out::print);

Which modification enables the code fragment to compile?

A. Replace line n1 with:
IntFunction<UnaryOperator> inFunc = x -> y -> x * y;
B. Replace line n1 with:
IntFunction<IntUnaryOperator> inFunc = x -> y -> x * y;
C. Replace line n1 with:
BiFunction<IntUnaryOperator> inFunc = x -> y -> x * y;
D. Replace line n2 with:
IntStream result = inStr.map(inFunc.applyAsInt(4));

Stage 3 Problem 92 (view answer and explanation)

Given:

public class LetterFromJane {
    public static void main(String[] args) {
        StringBuilder letter = new StringBuilder("Dear John");
        int indx = 0;
        try {
            for (indx = 0; indx < 10; indx++) {
                switch (letter.charAt(indx)) {
                    case 'a':
                    case 'e':
                    case 'o':
                        String uc = Character.toString(letter.charAt(indx)).toUpperCase();
                        letter.replace(indx, indx + 1, uc);
                }
            }
        } catch (Exception e) {
            System.out.println("Goodbye.");
        }
        System.out.println(letter);
    }
}

What is the result?

A. DEAr JOhn
B. Dear John
C. Goodbye.
DEAr JOhn
D. Goodbye.

Stage 3 Problem 93 (view answer and explanation)

Given the code fragments:

public class Stock implements Comparator<Stock> {
    String ticker;
    double price;
    public Stock() {
    }
    public Stock(String ticker, double price) {
        this.ticker = ticker;
        this.price = price;
    }
    public int compare(Stock s1, Stock s2) {
        return s1.ticker.compareTo(s2.ticker);
    }
    public String toString() {
        return ticker + ":" + price;
    }
}

and

List<Stock> portfolio = Arrays.asList(
        new Stock("MSFT", 74),
        new Stock("GOOGL", 952));
Collections.sort(portfolio, new Stock());
System.out.print(portfolio);

What is the result?

A. [GOOGL:952.0, MSFT:74.0]
B. [MSFT:74.0, GOOGL:952.0]
C. A compilation error occurs because the Stock class does not override the abstract method compareTo().
D. An Exception is thrown at run time.

Stage 3 Problem 94 (view answer and explanation)

Given:

public interface Printable<Integer> {
    public default void printOnDemand(Integer copies) {
        System.out.println("Printing on demand.");
    }
    public void offsetPrinting(Integer copies);
}

Which statement is true?

A. Printable can be used as below:

Printable<Integer> publisher = x -> System.out.println("Printing " + x + " copies.");
publisher.offsetPrinting(100000);
publisher.printOnDemand(2);

B. Printable can be used as below:

Printable<Integer> publisher = x -> x + 10;
publisher.offsetPrinting(100000);
publisher.printOnDemand(2);

C. Printable can be used as below:

Printable publisher = (Integer x) -> System.out.println(x);
publisher.offsetPrinting(100000);
Printable.printOnDemand(2);

D. Printable cannot be used in a lambda expression.

Stage 3 Problem 95 (view answer and explanation)

Which two code blocks correctly initialize a Locale variable?

A. Locale loc1 = “JP”;
B. Locale loc2 = Locale.getInstance(“fr”);
C. Locale loc3 = Locale.getLocaleFactory(“FR”);
D. Locale loc4 = Locale.GERMANY;
E. Locale loc5 = new Locale(“fr”, “FR”);

Stage 3 Problem 96 (view answer and explanation)

Given:

ExamTaker.java:

public class ExamTaker {

    private String fName;
    private String lName;
    private static int count;

    public ExamTaker(String first, String last) {
        fName = first;
        lName = last;
        ++count;
    }

    static {
        count = 0;
    }

    public static int getCount() {
        return count;
    }
}

Test.java:

public class Test {

    public static void main(String[] args) {
        ExamTaker et1 = new ExamTaker("Alice", "Adams");
        ExamTaker et2 = new ExamTaker("Bob", "Barry");
        ExamTaker et3 = new ExamTaker("Chuck", "Collins");
        ExamTaker et4 = new ExamTaker("Doug", "Dowson");
        et4 = null;
        et3 = et2;
        System.out.println(ExamTaker.getCount());
    }
}

What is the result?

A. 0
B. 2
C. 3
D. 4
E. 5

Stage 3 Problem 97 (view answer and explanation)

Given the code fragment:

List<String> archives = Arrays.asList("ZIP", "RAR", "TAR");
archives.forEach(x -> System.out.print(x + " "));
String common = archives.stream()
     .filter(x -> x.contains("AR"))
     .reduce((x, y) -> x + y).get();
System.out.println("\n" + common);

What is the result?

A. ZIP RAR TAR
RARTAR
B. ZIP RAR RARTAR
RARRARTAR
C. RARTAR
RARTAR
D. The order of the output is unpredictable.

Stage 3 Problem 98 (view answer and explanation)

For which three objects must a vendor provide implementations in its JDBC driver?

A. Time
B. Date
C. Statement
D. ResultSet
E. Connection
F. SQLException
G. DriverManager

Stage 3 Problem 99 (view answer and explanation)

Given:

class Car {
    private List<Wheel> wheels;
    public Car(){
        wheels = Arrays.asList(
                new Wheel(),
                new Wheel(),
                new Wheel(),
                new Wheel());
    }
    public List<Wheel> getWheels() {
        return wheels;
    }
}

class Wheel {
    private int airPressure;
    public Wheel(){
        airPressure = (int)(Math.random()*100);  // sets airPressure randomly
    }                                            // from 0 to 99 inclusive
    public int getAirPressure() {
        return airPressure;
    }
}

class Test{
    public static void main(String[] args) {
        List<Car> cars = Arrays.asList(new Car(), new Car(), new Car());
        System.out.println(cars.stream()
                               .map(Car::getWheels)                // line n1
                               .flatMap(Wheel::stream)             // line n2
                               .mapToInt(Wheel::getAirPressure)    // line n3
                               .max()                              // line n4
                               .isPresent()                        // line n5
        );
   }
}

Which two modifications, when applied together, will let the code find the maximum value of air pressure of all wheels in all the cars?

A. Remove line n5
B. Replace line n5 with
.orElse(12345)
C. Replace line n2 with
.flatMapToInt(List::stream)
D. Replace line n2 with
.flatMap(List::stream)
E. Replace line n3 with
.flatMap(Wheel::getAirPressure)
F. Replace line n5 with
.ifPresent(Wheel::getAirPressure)

Stage 3 Problem 100 (view answer and explanation)

Given:

String str = "I been a idiot since I was born. My IQ is near 70, which qualifies me, so they say.";   // line n1
Optional<String> result = Stream.of(str.split("[ ,.]")).anyMatch(x->x.startsWith("I"));               // line n2
System.out.println(result.get());                                                                     // line n3

Which one of the following statements is correct?

A. The code prints either I or IQ.
B. The code always prints I.
C. The code prints I if lines n2 and n3 are changed to:

String result = Stream.of(sentence.split("[ ,.]")).anyMatch(x->x.startsWith("I"));                  // line n2
System.out.println(result.get());                                                                   // line n3

D. The code prints either I or IQ if lines n2 and n3 are changed to:

Optional<String> result = Stream.of(str.split("[ ,.]")).parallel().anyMatch(x->x.startsWith("I"));  // line n2
System.out.println(result.get());                                                                   // line n3

E. The code fails to compile.

Leave Comment

Your email address will not be published.