Question 1
Question
1. What is the result of executing the following code snippet?
41: final int score1 = 8, score2 = 3;
42: char myScore = 7;
43: var goal = switch (myScore) {
44: default -> {if(10>score1) yield "unknown";}
45: case score1 -> "great";
46: case 2, 4, 6 -> "good";
47: case score2, 0 -> {"bad";}
48: };
49: System.out.println(goal);
Question 2
Question
2. What is the output of the following code snippet?
int moon = 9, star = 2 + 2 * 3;
float sun = star>10 ? 1 : 3;
double jupiter = (sun + moon) - 1.0f;
int mars = --moon <= 8 ? 2 : 3;
System.out.println(sun+", "+jupiter+", "+mars);
Question 3
Question
3. Which changes, when made independently, guarantee the following code snippet
prints 100 at runtime? (Choose all that apply.)
List<Integer> data = new ArrayList<>();
IntStream.range(0,100).parallel().forEach(s -> data.add(s));
System.out.println(data.size());
Answer
-
A. Change data to an instance variable and mark it volatile.
-
B. Remove parallel() in the stream operation.
-
C. Change forEach() to forEachOrdered() in the stream operation.
-
D. Change parallel() to serial() in the stream operation.
-
E. Wrap the lambda body with a synchronized block.
-
F. The code snippet will always print 100 as is.
Question 4
Question
4. What is the output of this code?
20: Predicate<String> empty = String::isEmpty;
21: Predicate<String> notEmpty = empty.negate();
22:
23: var result = Stream.generate(() -> "")
24: .filter(notEmpty)
25: .collect(Collectors.groupingBy(k -> k))
26: .entrySet()
27: .stream()
28: .map(Entry::getValue)
29: .flatMap(Collection::stream)
30: .collect(Collectors.partitioningBy(notEmpty));
31: System.out.println(result);
Answer
-
A. It outputs {}.
-
B. It outputs {false=[], true=[]}.
-
C. The code does not compile.
-
D. The code does not terminate.
Question 5
Question
5. What is the result of the following program?
1: public class MathFunctions {
2: public static void addToInt(int x, int amountToAdd) {
3: x = x + amountToAdd;
4: }
5: public static void main(String[] args) {
6: var a = 15;
7: var b = 10;
8: MathFunctions.addToInt(a, b);
9: System.out.println(a); } }
Question 6
Question
6. Suppose that we have the following property files and code. What values are printed
on lines 8 and 9, respectively?
Penguin.properties
name=Billy
age=1
Penguin_de.properties
name=Chilly
age=4
Penguin_en.properties
name=Willy
5: Locale fr = new Locale("fr");
6: Locale.setDefault(new Locale("en", "US"));
7: var b = ResourceBundle.getBundle("Penguin", fr);
8: System.out.println(b.getString("name"));
9: System.out.println(b.getString("age"));
Question 7
Question
7. What is guaranteed to be printed by the following code? (Choose all that apply.)
int[] array = {6,9,8};
System.out.println("B" + Arrays.binarySearch(array,9));
System.out.println("C" + Arrays.compare(array,
new int[] {6, 9, 8}));
System.out.println("M" + Arrays.mismatch(array,
new int[] {6, 9, 8}));
Question 8
Question
8. Which functional interfaces complete the following code, presuming variable r
exists? (Choose all that apply.)
6: ______ x = r.negate();
7: ______ y = () -> System.out.println();
8: ______ z = (a, b) -> a - b;
Question 9
Question
9. Suppose you have a module named com.vet. Where could you place the following
module-info.java file to create a valid module?
public module com.vet {
exports com.vet;
}
Question 10
Question
10. What is the output of the following program? (Choose all that apply.)
1: interface HasTail { private int getTailLength(); }
2: abstract class Puma implements HasTail {
3: String getTailLength() { return "4"; }
4: }
5: public class Cougar implements HasTail {
6: public static void main(String[] args) {
7: var puma = new Puma() {};
8: System.out.println(puma.getTailLength());
9: }
10: public int getTailLength(int length) { return 2; }
11: }
Answer
-
A. 2
-
B. 4
-
C. The code will not compile because of line 1.
-
D. The code will not compile because of line 3.
-
E. The code will not compile because of line 5.
-
F. The code will not compile because of line 7.
-
G. The code will not compile because of line 10.
-
H. The output cannot be determined from the code provided.
Question 11
Question
11. Which lines in Tadpole.java give a compiler error? (Choose all that apply.)
// Frog.java
1: package animal;
2: public class Frog {
3: protected void ribbit() { }
4: void jump() { }
5: }
// Tadpole.java
1: package other;
2: import animal.*;
3: public class Tadpole extends Frog {
4: public static void main(String[] args) {
5: Tadpole t = new Tadpole();
6: t.ribbit();
7: t.jump();
8: Frog f = new Tadpole();
9: f.ribbit();
10: f.jump();
11: } }
Question 12
Question
12. Which of the following can fill in the blanks in order to make this code compile?
__________ a = __________.getConnection(
url, userName, password);
__________ b = a.prepareStatement(sql);
__________ c = b.executeQuery();
if (c.next()) System.out.println(c.getString(1));
Answer
-
A. Connection, Driver, PreparedStatement, ResultSet
-
B. Connection, DriverManager, PreparedStatement, ResultSet
-
C. Connection, DataSource, PreparedStatement, ResultSet
-
D. Driver, Connection, PreparedStatement, ResultSet
-
E. DriverManager, Connection, PreparedStatement, ResultSet
-
F. DataSource, Connection, PreparedStatement, ResultSet
Question 13
Question
13. Which of the following statements can fill in the blank to make the code compile
successfully? (Choose all that apply.)
Set<? extends RuntimeException> mySet = new _________ ();
Answer
-
A. HashSet<? extends RuntimeException>
-
B. HashSet<Exception>
-
C. TreeSet<RuntimeException>
-
D. TreeSet<NullPointerException>
-
E. None of the above
Question 14
Question
14. Assume that birds.dat exists, is accessible, and contains data for a Bird object.
What is the result of executing the following code? (Choose all that apply.)
1: import java.io.*;
2: public class Bird {
3: private String name;
4: private transient Integer age;
5:
6: // Getters/setters omitted
7:
8: public static void main(String[] args) {
9: try(var is = new ObjectInputStream(
10: new BufferedInputStream(
11: new FileInputStream("birds.dat")))) {
12: Bird b = is.readObject();
13: System.out.println(b.age);
14: } } }
Answer
-
A. It compiles and prints 0 at runtime.
-
B. It compiles and prints null at runtime.
-
C. It compiles and prints a number at runtime.
-
D. The code will not compile because of lines 9–11.
-
E. The code will not compile because of line 12.
-
F. It compiles but throws an exception at runtime.
Question 15
Question
15. Which of the following are valid instance members of a class? (Choose all that
apply.)
Question 16
Question
16. Which is true if the table is empty before this code is run? (Choose all that apply.)
var sql = "INSERT INTO people VALUES(?, ?, ?)";
conn.setAutoCommit(false);
try (var ps = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE)) {
ps.setInt(1, 1);
ps.setString(2, "Joslyn");
ps.setString(3, "NY");
ps.executeUpdate();
Savepoint sp = conn.setSavepoint();
ps.setInt(1, 2);
ps.setString(2, "Kara");
ps.executeUpdate();
conn._________________;
}
Answer
-
A. If the blank line contains rollback(), there are no rows in the table.
-
B. If the blank line contains rollback(), there is one row in the table.
-
C. If the blank line contains rollback(sp), there are no rows in the table.
-
D. If the blank line contains rollback(sp), there is one row in the table.
-
E. The code does not compile.
-
F. The code throws an exception because the second update does not set all the
parameters.
Question 17
Question
17. Which is true if the contents of path1 start with the text Howdy? (Choose two.)
System.out.println(Files.mismatch(path1,path2));
Answer
-
A. If path2 doesn't exist, the code prints -1.
-
B. If path2 doesn't exist, the code prints 0.
-
C. If path2 doesn't exist, the code throws an exception.
-
D. If the contents of path2 start with Hello, the code prints -1.
-
E. If the contents of path2 start with Hello, the code prints 0.
-
F. If the contents of path2 start with Hello, the code prints 1.
Question 18
Question
18. Which of the following types can be inserted into the blank to allow the program to
compile successfully? (Choose all that apply.)
1: import java.util.*;
2: final class Amphibian {}
3: abstract class Tadpole extends Amphibian {}
4: public class FindAllTadpoles {
5: public static void main(String… args) {
6: var tadpoles = new ArrayList<Tadpole>();
7: for (var amphibian : tadpoles) {
8: ___________ tadpole = amphibian;
9: } } }
Answer
-
A. List<Tadpole>
-
B. Boolean
-
C. Amphibian
-
D. Tadpole
-
E. Object
-
F. None of the above
Question 19
Question
19. What is the result of compiling and executing the following program?
1: public class FeedingSchedule {
2: public static void main(String[] args) {
3: var x = 5;
4: var j = 0;
5: OUTER: for (var i = 0; i < 3;)
6: INNER: do {
7: i++;
8: x++;
9: if (x> 10) break INNER;
10: x += 4;
11: j++;
12: } while (j <= 2);
13: System.out.println(x);
14: } }
Question 20
Question
20. When printed, which String gives the same value as this text block?
var pooh = """
"Oh, bother." -Pooh
""".indent(1);
System.out.print(pooh);
Answer
-
A. "\n\"Oh, bother.\" -Pooh\n"
-
B. "\n \"Oh, bother.\" -Pooh\n"
-
C. " \"Oh, bother.\" -Pooh\n"
-
D. "\n\"Oh, bother.\" -Pooh"
-
E. "\n \"Oh, bother.\" -Pooh"
-
F. " \"Oh, bother.\" -Pooh"
-
G. None of the above
Question 21
Question
21. A(n) _________________ module always contains a module-info.java file,
while a(n) _________________ module always exports all its packages to other
modules.
Answer
-
A. automatic, named
-
B. automatic, unnamed
-
C. named, automatic
-
D. named, unnamed
-
E. unnamed, automatic
-
F. unnamed, named
-
G. None of the above
Question 22
Question
22. What is the result of the following code?
22: var treeMap = new TreeMap<Character, Integer>();
23: treeMap.put('k', 1);
24: treeMap.put('k', 2);
25: treeMap.put('m', 3);
26: treeMap.put('M', 4);
27: treeMap.replaceAll((k, v) -> v + v);
28: treeMap.keySet()
29: .forEach(k -> System.out.print(treeMap.get(k)));
Answer
-
A. 268
-
B. 468
-
C. 2468
-
D. 826
-
E. 846
-
F. 8246
-
G. None of the above
Question 23
Question
23. Which of the following lines can fill in the blank to print true? (Choose all that
apply.)
10: public static void main(String[] args) {
11: System.out.println(test(____________________________));
12: }
13: private static boolean test(Function<Integer, Boolean> b) {
14: return b.apply(5);
15: }
Question 24
Question
24. How many times is the word true printed?
var s1 = "Java";
var s2 = "Java";
var s3 = s1.indent(1).strip();
var s4 = s3.intern();
var sb1 = new StringBuilder();
sb1.append("Ja").append("va");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s1 == s3);
System.out.println(s1 == s4);
System.out.println(sb1.toString() == s1);
System.out.println(sb1.toString().equals(s1));
Question 25
Question
25. What is the output of the following program?
1: class Deer {
2: public Deer() {System.out.print("Deer");}
3: public Deer(int age) {System.out.print("DeerAge");}
4: protected boolean hasHorns() { return false; }
5: }
6: public class Reindeer extends Deer {
7: public Reindeer(int age) {System.out.print("Reindeer");}
8: public boolean hasHorns() { return true; }
9: public static void main(String[] args) {
10: Deer deer = new Reindeer(5);
11: System.out.println("," + deer.hasHorns());
12: } }
Question 26
Question
26. Which of the following are true? (Choose all that apply.)
private static void magic(Stream<Integer> s) {
Optional o = s
.filter(x -> x < 5)
.limit(3)
.max((x, y) -> x-y);
System.out.println(o.get());
}
Answer
-
A. magic(Stream.empty()); runs infinitely.
-
B. magic(Stream.empty()); throws an exception.
-
C. magic(Stream.iterate(1, x -> x++)); runs infinitely.
-
D. magic(Stream.iterate(1, x -> x++)); throws an exception.
-
E. magic(Stream.of(5, 10)); runs infinitely.
-
F. magic(Stream.of(5, 10)); throws an exception.
-
G. The method does not compile.
Question 27
Question
27. Assuming the following declarations are top-level types declared in the same file,
which successfully compile? (Choose all that apply.)
record Music() {
final int score = 10;
} record Song(String lyrics) {
Song {
this.lyrics = lyrics + "Hello World";
}
} sealed class Dance {}
record March() {
@Override String toString() { return null; }
} class Ballet extends Dance {}
Answer
-
A. Music
-
B. Song
-
C. Dance
-
D. March
-
E. Ballet
-
F. None of them compile.
Question 28
Question
28. Which of the following expressions compile without error? (Choose all that apply.)
Answer
-
A. int monday = 3 + 2.0;
-
B. double tuesday = 5_6L;
-
C. boolean wednesday = 1 > 2 ? !true;
-
D. short thursday = (short)Integer.MAX_VALUE;
-
E. long friday = 8.0L;
-
F. var saturday = 2_.0;
-
G. None of the above
Question 29
Question
29. What is the result of executing the following application?
final var cb = new CyclicBarrier(3,
() -> System.out.println("Clean!")); // u1
ExecutorService service = Executors.newSingleThreadExecutor();
try {
IntStream.generate(() -> 1)
.limit(12)
.parallel()
.forEach(i -> service.submit(() -> cb.await())); // u2
} finally { service.shutdown(); }
Answer
-
A. It outputs Clean! at least once.
-
B. It outputs Clean! exactly four times.
-
C. The code will not compile because of line u1.
-
D. The code will not compile because of line u2.
-
E. It compiles but throws an exception at runtime.
-
F. It compiles but waits forever at runtime.
Question 30
Question
30. Which statement about the following method is true?
5: public static void main(String… unused) {
6: System.out.print("a");
7: try (StringBuilder reader = new StringBuilder()) {
8: System.out.print("b");
9: throw new IllegalArgumentException();
10: } catch (Exception e || RuntimeException e) {
11: System.out.print("c");
12: throw new FileNotFoundException();
13: } finally {
14: System.out.print("d");
15: } }
Answer
-
A. It compiles and prints abc.
-
B. It compiles and prints abd.
-
C. It compiles and prints abcd.
-
D. One line contains a compiler error.
-
E. Two lines contain a compiler error.
-
F. Three lines contain a compiler error.
-
G. It compiles but prints an exception at runtime.