Assessment Flashcards

1
Q

What is a possible output of the following?

var trainDay = LocalDate.of(2022, 5, 14);
var time = LocalTime.of(10, 0);
var zone = ZoneId.of("America/Los_Angeles");
var zdt = ZonedDateTime.of(trainDay, time, zone);

var instant = zdt.toInstant();
instant = instant.plus(1, ChronoUnit.YEARS);
System.out.println(instant);
A

While an Instant represents a specific moment in time using GMT, Java only allows adding or removing units of DAYS or smaller. This code throws an UnsupportedTemporalTypeException because of the attempt to add YEARS.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

generic

A
  • ? extends RuntimeException cannot be assigned a broader type.
  • any type of generic list can go in List˂?˃
  • ? super RuntimeException does allow a broader exception type.
  • You can’t use generics with a primitive
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Modules

A

Which are true of jlink? (Choose two.)
B. At least the modules specified by –add-modules are included in the runtime image.
E. The output is a directory.

jdeps
E. jdeps -jdkinternals sneaky.jar
F. jdeps –jdk-internals sneaky.jar

Which are true statements about the majority of steps in migrating to a modular application? (Choose two.)
C. In a bottom-up migration, unnamed modules turn into named modules.
D. In a top-down migration, automatic modules turn into named modules.
A fully modular application has all named modules, making options B and E incorrect. A bottom-up migration starts out with unnamed modules, making option C correct. By contrast, a top-down migration starts by making all modules automatic modules, making option D correct.

The service locator contains a ServiceLoader call to the load() method to look up,
The ServiceLoader.load() method needs to be called to get an instance before calling stream().

Unnamed modules are always on the classpath. Both automatic and named modules are on the module path. Named modules always contain a module-info file, but automatic modules never do. Option E is correct, as it meets both these criteria.

The javac command uses -p and –module-path to supply the module path. There are two valid long forms of the classpath option: -classpath and –class-path. Options A and C match these.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the output of the following?

var list = Arrays.asList("flower", "seed", "plant");
Collections.sort(list);
Collections.reverse(list);

var result = Collections.binarySearch(list,
   list.get(0), Comparator.reverseOrder());
System.out.println(result);
A

A. 0

First, the list is sorted ascendingly. Then it is reversed so it is in descending order. Since our binary search also uses descending order, we meet the pre-condition for binary search. At this point, the list contains [seed, plant, flower]. The key is to notice that the first element is now seed rather than flower. Calling a binary search to find the position of seed returns 0, which is the index matching that value. Therefore, the answer is option A.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the output of the following?

var builder = new StringBuilder("Leaves growing");
do {
   builder.delete(0, 5);
} while (builder.length() ˃ 5);
System.out.println(builder);
A
  • On the first iteration through the loop, the first five characters are removed, and builder becomes “s growing”.
  • Since there are more than five characters left, the loop iterates again. This time, five more characters are removed, and builder becomes “wing”.
  • This matches option C.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the following output?

var dice = new LinkedList˂Integer˃();
dice.offer(3);
dice.offer(2);
dice.offer(4);
System.out.print(dice.stream().filter(n -˃ n != 4));
A
  • The code correctly creates a LinkedList with three elements. The stream pipeline does compile.
  • However, there is no terminal operation, which means the stream is never evaluated, and the output is something like java.util.stream.ReferencePipeline$2@404b9385.
  • This is definitely not one of the listed choices, so option E is correct.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Operator

A
  • bitwise complement by negating the value and subtracting one.
  • instanceof
    • You are allowed to use null with instanceof; it just prints false.
    • Then it gets interesting. We know that bus is not an ArrayList or Collection. However, the compiler only knows that bus is not an ArrayList because ArrayList is a concrete class.
      ~~~
      System.out.println(bus instanceof ArrayList);
      ~~~
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Assuming the current locale uses dollars ($) and the following method is called with a double value of 960_010, which of the following values are printed? (Choose two.)

public void print(double t) {
   System.out.print(NumberFormat.getCompactNumberInstance().format(t));

   System.out.print(
      NumberFormat.getCompactNumberInstance(
         Locale.getDefault(), Style.SHORT).format(t));

   System.out.print(NumberFormat.getCurrencyInstance().format(t));
}
A

The code compiles and runs without issue. When a CompactNumberFormat instance is requested without a style, it uses the SHORT style by default. This results in both of the first two statements printing 960K, making option A correct. Option D is also correct, as the full value is printed with a currency formatter without rounding.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

JDBC

A

The ResultSet interface does not have a hasNext() method.

prepareCall() returns a CallableStatement.

stored procedure

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the result of calling this method?

16: void play() {
17:    record Toy(String name){ }
18: 
19:    var toys = Stream.of(
20:       new Toy("Jack in the Box"), 
21:       new Toy("Slinky"), 
22:       new Toy("Yo-Yo"), 
23:       new Toy("Rubik's Cube"));
24:
25:    var spliterator = toys.spliterator();
26:    var batch1 = spliterator.trySplit();
27:    var batch2 = spliterator.trySplit();
28:    var batch3 = spliterator.trySplit();
29:
30:    batch1.forEachRemaining(System.out::print);
31: }
A

Line 25 creates a Spliterator containing four toys. Line 26 splits them into two equal groups by removing the first half of the elements and making them available to batch1. These get printed on line 30, making option E the answer. Note that the splits on lines 27 and 28 are meaningless since batch1 has already been split off.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the output of the following application?

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 void dress() {
final 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();
} }

A

The code does not compile because the Jacket is marked final and cannot be extended by the anonymous class declared on line v2. Since this line doesn’t compile, option D is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Exception

A

The second catch block on line p2 does not compile. Since IllegalArgumentException is a subclass of Exception, they cannot be used in the same multi-catch block since it is redundant.

Line 9 is not reachable and does not compile, since FileNotFoundException is a subclass of IOException, which has already been caught. Next, the local variable e is declared twice within the same scope, with the declaration on line 12 failing to compile. Finally, the openDrawbridge() method declares the checked Exception class, but it is not handled or declared in the main() method on line 21. Since lines 9, 12, and 21 need to be changed for the code to compile, option D is correct.

ClassCastException is a runtime exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Collection

A

ArrayDeque

Collectors.teeing(Collectors.counting(), Collectors.summingInt(Pet::age))

A teeing() collector takes three parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Concurrency

A

To perform a concurrent reduction, the stream or the collector must be unordered. Since it is possible to use an ordered collector with an unordered stream and achieve a parallel reduction, option A is incorrect. Option B is also incorrect. While having a thread-safe collection is preferred, it is not required. Stateful lambda expressions should be avoided, whether the stream is serial or parallel, making option C incorrect. Option D is incorrect as there is no class/interface within the JDK called ParallelStream. Options E and F are correct statements about performing parallel reductions.

ExecutorService.submit() that takes a Runnable expression, it returns Future˂?˃, since the return type is void.

The parallelStream() method is found in the Collection interface, not the Stream interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

enum

A

enum constructors cannot be public
case statement must use an enum value without the type.
A semicolon is required after a list of enum values if the enum contains anything besides the list of values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Inner class

A

Which of the following statements about nested classes are correct? (Choose three.)
B. All nested classes can contain constant variables.
C. A local class can declare that it implements multiple interfaces.
E. A static nested class can contain static methods.

Options B, C, and E are valid statements about nested classes. An anonymous class can declare only one supertype, either a class or an interface, making option A incorrect. A member inner class can contain static methods, making option D incorrect. A local class can access only final and effectively final local variables, making option F incorrect.

17
Q

locale

A
18
Q

How many lines contain a compiler error?

1: public record Bee(boolean gender, String species) {
2: Bee {
3: this.gender = gender;
4: this.species = species;
5: }
6: Bee(boolean gender) {
7: this(gender, “Honeybee”);
8: }
9: @Override public String getSpecies() {
10: return species;
11: }
12: @Override public String toString() {
13: return species;
14: } }

A

Line 2 does not compile because a compact constructor must have the same public access as the record itself. Lines 3 and 4 do not compile because compact constructors cannot set field values with this. They can only modify constructor parameters. The constructor on line 6 compiles, as the access modifier does not need to match for non-compact constructors and chained constructors. Line 9 does not compile because species() is supplied by the record, which does not match getSpecies(). In this case, using the @Override annotation triggers a compiler error. Finally, the toString() override is correct. Since four lines do not compile, option E is the answer.

19
Q

How many of these classes cause a compiler error?

final class Chimp extends Primate { }
non-sealed class Bonabo extends Primate { }
final class Gorilla { }
public abstract sealed class Primate permits Chimp, Bonabo {
abstract String getName();
}

A. Zero
B. One
C. Two
D. Three
E. Four

A

You Answered Correctly!
The Chimp and Bonabo classes do not compile because they do not implement the abstract getName() method. This gives us two compiler errors and the answer of option C.

20
Q

What is the result of the following?

import java.util.*;
public class Museums {
   public static void main(String[] args) {
      String[] array = {"Natural History", "Science", "Art"};
      List˂String˃ museums = Arrays.asList(array);
      museums.remove(2);
      System.out.println(museums);
   } }
A

When converting an array to a List, Java uses a fixed-length backed list. This means that the list uses an array in the implementation. While changing elements to new values is allowed, adding and removing elements is not, making option D the answer.

21
Q

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
} }

A. The code doesn’t compile due to line c1.
B. The code doesn’t compile due to line c2.
C. The code doesn’t compile due to line c3.
D. The code compiles and runs without output.
E. The code compiles but throws an exception at runtime.
You Answered Correctly!
This code actually does compile. Line c1 is fine because the method uses the ? wildcard, which allows any collection. Line c2 is a standard method declaration. Line c3 looks odd, but it does work. The lambda takes one parameter and does nothing with it. Since there is no output, option D is correct.

A
22
Q

Arrays

A
    • When the arrays are the same, the compare() method returns 0,
  • while the mismatch() method returns -1.
  • mismatch() returns the index of the first element that is different.
23
Q

I/O

A

The readObject() method returns an Object instance, which must be explicitly cast to Cruise in the second try-with-resources statement.

24
Q

seal class

A

public sealed class First { }
A. Chicken and Egg must be classes.
D. Chicken and Egg must be located in the same file as First.

Chicken and Egg must be subclasses of First since interfaces, enums, and records can’t extend a class. This gives us option A as one of the answers. Since the permits clause is not specified, Chicken and Egg may or may not be nested classes, but they must be in the same file as First. Therefore, option D is the other answer.

25
Q

Comparable/Comparator

A

C. The compare() and compareTo() methods have the same contract for the return value.
D. It is possible to sort the same List using different Comparator implementations.

Comparable is implemented in the class being compared
a Comparator is often implemented with a lambda.
compareTo() is the method in Comparable.
comparators are not required to be consistent with the equals() method.

26
Q

Stream

A

1: package reader;
2: import java.util.stream.*;
3: public class Books {
4: public static void main(String[] args) {
5: IntStream pages = IntStream.of(200, 300);
6: long total = pages.sum();
7: long count = pages.count();
8: System.out.println(total + “-“ + count);
9: } }

  • All the primitive stream types use long as the return type for count().
  • line 7 throws an IllegalStateException because the stream has already been used. Both sum() and count() are terminal operations, and only one terminal operation is allowed on the same stream.
  • two terminal operations, forEach() and count(). Only one terminal operation is allowed, so the code does not compile
27
Q

Interface

A
  • interface methods cannot be marked protected.
  • override the interface method to be package access. Since this reduces the implied visibility of protected
  • An overriding method cannot declare any new or broader checked exceptions than the overridden method.
    • FileNotFoundException is a narrower exception than IOException.
    • NumberFormatException new unchecked exceptions are allowed
    • not throwing any exceptions is also permitted in overridden methods.
  • The ElectricBass class does not compile, since it inherits two default methods with the same signature. Even though the class is marked abstract, it still must override this default method.