Java chapter 5
What is the result of the following code? 1: public record Hello<T>(T t) {2: public Hello(T t) { this.t = t; }3: private <T> void println(T message) {4: System.out.print(t + "-" + message);5: }6: public static void main(String[] args) {7: new Hello<String>("hi").println(1);8: new Hello("hola").println(true);9: } }
hi-1hola-true
Which lambda can replace the MySecret class to return the same value? (Select the two choices that apply) interface Secret { String magic(double d);} class MySecret implements Secret { public String magic(double d) { return "Poof"; } }
"(e) -> {"Poof"}" is incorrect because it does not use the return keyword. All options which use "String e =" are incorrect because the variable e is already in use from the lambda and cannot be redefined. These options are also invalid because one is missing the return keyword and one is missing a required semicolon.
Which of the following are valid lambda expressions? (Select the two choices that apply) (Wolf w, var c) -> 39 (var y) -> return 0; (final Camel c) -> {} (a,b,c) -> {int b = 3; return 2;} (Cat a, b) -> {} () -> {float r} (x,y) -> new RuntimeException()
"(final Camel c) -> {}" is a valid functional interface, one that could be assigned to a Consumer<Camel> reference. Notice that the final modifier is permitted on variables in the parameter list. "(x,y) -> new RuntimeException()" is correct, as the exception is being returned as an object and not thrown. This would be compatible with a BiFunction that included RuntimeException as its return type. "(Wolf w, var c) -> 39" and "(Cat a, b) -> {}" are incorrect because they mix format types for the parameters. "(a,b,c) -> {int b = 3; return 2;}" is invalid because the variable b is used twice. "(var y) -> return 0;" is incorrect, as a return statement is permitted only inside braces ({}). "() -> {float r}" is incorrect because the variable declaration requires a semicolon (;) after it.
Which lambdas can replace thenew Sloth() call in themain() method and produce the same output at runtime? import java.util.List;interface Yawn { String yawn(double d, List<Integer> time);}class Sloth implements Yawn { public String yawn(double zzz, List<Integer> time) { return "Sleep: " + zzz; } }public class Vet { public static String takeNap(Yawn y) { return y.yawn(10, null); } public static void main(String... unused) { System.out.print(takeNap(new Sloth())); } }
"(z,f) -> { String x = ""; return "Sleep: " + x }" does not compile because the second statement within the block is missing a semicolon (;) at the end. "(t,s) -> { String t = ""; return "Sleep: " + t; }" is an invalid lambda expression because t is defined twice: in the parameter list and within the lambda expression. "(w,q) -> {"Sleep: " + w}" and "(e,u) -> { String g = ""; "Sleep: " + e }" are both missing a return statement and semicolon. "(a,b) -> "Sleep: " + (double)(b==null ? a : a)" and "(r,k) -> { String g = ""; return "Sleep:"; }" are both valid lambda expressions, although only the former matches the behavior of the Sloth class. In particular, the latter only prints Sleep:, not Sleep: 10.0.
Which of the following is equivalent to this code? UnaryOperator<Integer> u = x -> x * x;
"Function<Integer, Integer> f = x -> x*x
Which of these statements compile? (Select the two choices that apply) List<> list = new ArrayList<String>(); HashSet<? super ClassCastException> set = new HashSet<Exception>(); List<Object> values = new HashSet<Object>(); HashSet<Number> hs = new HashSet<Integer>(); List<Object> objects = new ArrayList<? extends Object>(); Map<String, ? extends Number> hm = new HashMap<String, Integer>();
"HashSet<Number> hs = new HashSet<Integer>();" does not compile because the generic types are not compatible. We could say HashSet<? extends Number> hs2 = new HashSet<Integer>();. "HashSet<? super ClassCastException> set = new HashSet<Exception>();" uses a lower bound, so it allows superclass generic types. "List<> list = new ArrayList<String>();" does not compile because the diamond operator is allowed only on the right side. "List<Object> values = new HashSet<Object>();" does not compile because a Set is not a List. "List<Object> objects = new ArrayList<? extends Object>();" does not compile because upper bounds are not allowed when instantiating the type. "Map<String, ? extends Number> hm = new HashMap<String, Integer>();" does compile because the upper bound is on the correct side of the =.
Which lambda expression, when entered into the blank line in the following code, causes the program to printhahaha? (Select the two choices that apply) import java.util.function.Predicate;public class Hyena { private int age = 1; public static void main(String[] args) { var p = new Hyena(); double height = 10; int age = 1; testLaugh(p, _________________________); age = 2; } static void testLaugh(Hyena panda, Predicate<Hyena> joke) { var r = joke.test(panda) ? "hahaha" : "silence"; System.out.print(r); }}
"h -> h.age < 5" "var -> p.age <= 10"
Which options are true of the following code? (Select the two choices that apply) 3:______________ q = new LinkedList<>();4: q.add(10);5: q.add(12);6: q.remove(1);7: System.out.print(q);
A LinkedList implements both List and Queue. The List interface has a method to remove by index. Since this method exists, Java does not autobox to call the other method, making the output [10] and option A correct. Similarly, option C is correct because the method to remove an element by index is available on a LinkedList<Object> (which is what var represents here). By contrast, Queue has only the remove by object method, so Java does autobox there. Since the number 1 is not in the list, Java does not remove anything for the Queue, and the output is [10, 12].
Which statements about functional interfaces are true? (Select the two choices that apply)
A functional interface can contain any number of non-abstract methods, including default, private, static, and private static. Classes are never considered functional interfaces. A functional interface contains exactly one abstract method, although methods that have matching signatures as public methods in java.lang.Object do not count toward the single method test. While a functional interface can be marked with the @FunctionalInterface annotation, it is not required.
Which of the following are valid functional interfaces? (Select the three choices that apply) public interface Transport { public int go(); public boolean equals(Object o);} public abstract class Car { public abstract Object swim(double speed, int duration);} public interface Locomotive extends Train { public int getSpeed();} public interface Train extends Transport {} abstract interface Spaceship extends Transport { default int blastOff();} public interface Boat { int hashCode(); int hashCode(String input);}
A valid functional interface is one that contains a single abstract method, excluding any public methods that are already defined in the java.lang.Object class. Transport and Boat are valid functional interfaces, as they each contain a single abstract method: go() and hashCode(String), respectively. This gives us Boat and Transport. Since the other methods are part of Object, they do not count as abstract methods. Train is also a functional interface since it extends Transport and does not define any additional abstract methods. This adds Train as the final correct answer. Car is not a functional interface because it is an abstract class. Locomotive is not a functional interface because it includes two abstract methods, one of which is inherited. Finally, Spaceship is not a valid interface, let alone a functional interface, because a default method must provide a body. A quick way to test whether an interface is a functional interface is to apply the @FunctionalInterface annotation and check if the code still compiles.
Which of the following method signatures are valid overrides of the hairy() method in the Alpaca class? (Select the two choices that apply) import java.util.*;public class Alpaca { public List<String> hairy(List<String> list) { return null; }}
A valid override of a method with generic arguments must have a return type that is covariant, with matching generic type parameters. "public List<CharSequence> hairy(List<String> list) { return null; }" and "public Object hairy(List<String> list) { return null; }" are incorrect because the return type is too broad. Additionally, the generic arguments must have the same signature with the same generic types. This eliminates "public List<String> hairy(List<CharSequence> list) { return null; }" and "public List<String> hairy(List<Integer> list) { return null; }".
What is the result of the following code? 1: interface Climb {2: boolean isTooHigh(int height, int limit);3: }4:5: public class Climber {6: public static void main(String[] args) {7: check((h, m) -> h.append(m).isEmpty(), 5);8: }9: private static void check(Climb climb, int height) {10: if (climb.isTooHigh(height, 10))11: System.out.println("too high");12: else13: System.out.println("ok");14: }15: }
Compiler error on line 7
What is the result of the following code? 4: Map m = new HashMap();5: m.put(123, "456");6: m.put("abc", "def");7: System.out.println(m.contains("123"));
Compiler error on line 7
Which of the following functional interfaces contain an abstract method that returns a primitive value? (Select the three choices that apply)
DoubleSupplier and IntSupplier, BooleanSupplier
Suppose you need to display a collection of products for sale, which may contain duplicates. Additionally, you have a collection of sales that you need to track, sorted by the natural order of the sale ID, and you need to retrieve the text of each. Which two of the following from the java.util package best suit your needs for this scenario? (Select the two choices that apply)
For the first scenario, the answer needs to implement List because the scenario allows duplicates, narrowing it down to ArrayList and LinkedList. ArrayList is a better answer because LinkedList is both a List and a Queue, and you just need a regular List.For the second scenario, the answer needs to implement Map because you are dealing with key/value pairs per the unique id field. This narrows it down to HashMap and TreeMap. Since the question talks about ordering, you need the TreeMap.
Which of the following can be inserted without causing a compilation error? public void remove(List<Character> chars) { char end = 'z'; // INSERT LINE HERE Predicate<Character> predicate = c -> { char start = 'a'; return start <= c && c <= end; };}
Lambdas are not allowed to redeclare local variables, making "char start = 'a';" and "char c = 'x';" incorrect. "end = '1';" is incorrect because setting end prevents it from being effectively final. Lambdas are only allowed to reference final or effectively final variables. "chars = null;" compiles since chars is not used.
Which of the following are true? (Select the two choices that apply) 12: List<?> q = List.of("mouse", "parrot");13: var v = List.of("mouse", "parrot");14:15: q.removeIf(String::isEmpty);16: q.removeIf(s -> s.length() == 4);17: v.removeIf(String::isEmpty);18: v.removeIf(s -> s.length() == 4);
Line 12 creates a List<?>, which means it is treated as if all the elements are of type Object rather than String. Lines 15 and 16 do not compile since they call the String methods isEmpty() and length(), which are not defined on Object. Line 13 creates a List<String> because var uses the type that it deduces from the context. Lines 17 and 18 do compile. However, List.of() creates an immutable list, so both of those lines would throw an UnsupportedOperationException if run.
What is the result of the following class? 1: import java.util.function.*;2:3: public class Panda {4: int age;5: public static void main(String[] args) {6: Panda p1 = new Panda();7: p1.age = 1;8: check(p1, p -> p.age < 5);9: }10: private static void check(Panda panda,11: Predicate<Panda> pred) {12: String result =13: pred.test(panda) ? "match" : "not match";14: System.out.print(result);15: } }
Line 8 creates a lambda expression that checks whether the age is less than 5, printing "match". Since there is only one parameter and it does not specify a type, the parentheses around the parameter are optional. Lines 11 and 13 use the Predicate interface, which declares a test() method.
What is the result of running the following class? 1: import java.util.function.*;2:3: public class Panda {4: int age;5: public static void main(String[] args) {6: Panda p1 = new Panda();7: p1.age = 1;8: check(p1, p -> {p.age < 5});9: }10: private static void check(Panda panda,11: Predicate<Panda> pred) {12: String result = pred.test(panda)13: ? "match" : "not match";14: System.out.print(result);15: } }
Line 8 uses braces around the body. This means the return keyword and semicolon are required; the code does not compile.
Which of these statements compile? (Select the two choices that apply)
Map<String, ? extends Number> hm = new HashMap<String, Integer>(); HashSet<? super ClassCastException> set = new HashSet<Exception>();
Which of the following can fill in the blank to print [7, 5, 3]? (Select the two choices that apply) 8: public record Platypus(String name, int beakLength) {9: @Override public String toString() {return "" + beakLength;}10:11: public static void main(String[] args) {12: Platypus p1 = new Platypus("Paula", 3);13: Platypus p2 = new Platypus("Peter", 5);14: Platypus p3 = new Platypus("Peter", 7);15:16: List<Platypus> list = Arrays.asList(p1, p2, p3);17:18: Collections.sort(list, Comparator.comparing______);19:20: System.out.println(list);21: }22: }
Platypus::beakLength).reversed() (Platypus::name).thenComparingInt(Platypus::beakLength).reversed()
Which of the following lambda expressions can be passed to a function of Predicate<String> type? (Select the two choices that apply)
Predicate<String> takes a parameter list of one parameter using the specified type. StringBuilder is the wrong type. The arrow operator requires one hyphen (dash), not two.
Which of the following compiles and prints out the entire set? Set<?> set = Set.of("lion", "tiger", "bear");var s = Set.copyOf(set);Consumer<Object> consumer = ____________________;s.forEach(consumer);
System.out::println
Which statements are true? (Select the two choices that apply) The Predicate interface has a method named test(). The Supplier interface is good for printing out an existing value. The Function interface has a method named test(). The Consumer interface is good for printing out an existing value. The Predicate interface returns an int. The IntegerSupplier interface returns an int.
The Consumer interface is good for printing out an existing value IntSupplier does return an int
Which statements are true? (Select the two choices that apply) The Predicate interface returns an int. The Consumer interface is good for printing out an existing value. The Function interface has a method named test(). The IntegerSupplier interface returns an int. The Predicate interface has a method named test(). The Supplier interface is good for printing out an existing value.
The Consumer interface is good for printing out an existing value but the Supplier interface is not good for printing out an existing value because a Supplier returns a value while a Consumer takes one and acts on it. The IntegerSupplier is tricky. IntSupplier does return an int. However, the option asks about IntegerSupplier, which doesn't exist. A Predicate returns a boolean, not an int. Predicate does have a method named test(). Function has an apply() method, not test().
What does the following code output? Function<Integer, Integer> s = a -> a + 4;Function<Integer, Integer> t = a -> a * 3;Function<Integer, Integer> c = s.compose(t);System.out.print(c.apply(1));
The a.compose(b) method calls the Function parameter b before the reference Function variable a. In this case, that means that we multiply by 3 before adding 4. This gives a result of 7.
What is the result of the following program? 3: public class MyComparator implements Comparator<String> {4: public int compare(String a, String b) {5: return b.toLowerCase().compareTo(a.toLowerCase());6: }7: public static void main(String[] args) {8: String[] values = { "123", "Abb", "aab" };9: Arrays.sort(values, new MyComparator());10: for (var s: values)11: System.out.print(s + " ");12: }13: }
The array is sorted using MyComparator, which sorts the elements in reverse alphabetical order in a case-insensitive fashion. Normally, numbers sort before letters. This code reverses that by calling the compareTo() method on b instead of a.
Which is true of the following code? int length = 3; for (int i = 0; i<3; i++) { if (i%2 == 0) { Supplier<Integer> supplier = () -> length; // A System.out.println(supplier.get()); // B } else { int j = i; Supplier<Integer> supplier = () -> j; // C System.out.println(supplier.get()); // D }}
The code compiles successfully.
Which of these statements is true about the following code? public void method() { x((var x) -> {}, (var x, var y) -> false);}public void x(Consumer<String> x, BinaryOperator<Boolean> y) {}
The code compiles, and the x in each lambda refers to a different type.
What is the result of the following? var map = new HashMap<Integer, Integer>();map.put(1, 10);map.put(2, 20);map.put(3, null);map.merge(1, 3, (a,b) -> a + b);map.merge(3, 3, (a,b) -> a + b);System.out.println(map);
The first call to merge() calls the mapping function and adds the numbers to get 13. It then updates the map. The second call to merge() sees that the map currently has a null value for that key. It does not call the mapping function but instead replaces it with the new value of 3.
Which of the following will compile when filling in the blank? (Select the four choices that apply) var list = List.of(1, 2, 3);var set = Set.of(1, 2, 3);var map = Map.of(1, 2, 3, 4);_______.forEach(System.out::println);
The forEach() method works with a List or a Set. Therefore, list and set are correct. Additionally, map.keySet() and map.values() return a Set and can be used as well. map.keys() and map.valueSet() refer to methods that do not exist. map tricky because a Map does have a forEach() method. However, it uses two lambda parameters rather than one. Since there is no matching System.out.println method, it does not compile.
Which of the following will compile when filling in the blank? (Select the four choices that apply)var list = List.of(1, 2, 3);var set = Set.of(1, 2, 3);var map = Map.of(1, 2, 3, 4);_______.forEach(System.out::println);
The forEach() method works with a List or a Set. Therefore, list and set are correct. Additionally, map.keySet() and map.values() return a Set and can be used as well. map.keys() and map.valueSet() refer to methods that do not exist. map tricky because a Map does have a forEach() method. However, it uses two lambda parameters rather than one. Since there is no matching System.out.println method, it does not compile.
Which of these statements can fill in the blank so that the Helper class compiles successfully? (Select the three choices that apply) 2: public class Helper {3: public static <U extends Exception>4: void printException(U u) {5:6: System.out.println(u.getMessage());7: }8: public static void main(String[] args) {9: Helper.____________________________________;10: } }
The generic type must be Exception or a subclass of Exception since this is an upper bound, making "printException(new FileNotFoundException("A"))" and "printException(new Exception("B"))" correct. "<Throwable>printException(new Exception("C"))" and " printException(new Throwable("E"))" are wrong because Throwable is a superclass of Exception. Additionally, "<NullPointerException>printException(new NullPointerException ("D"))" is correct despite the odd syntax by explicitly listing the type. You should still be able to recognize it as acceptable.
What is the result of the following code? (Select the two choices that apply) 48: var map = Map.of(1,2, 3, 6);49: var list = List.copyOf(map.entrySet());50:51: List<Integer> one = List.of(8, 16, 2);52: var copy = List.copyOf(one);53: var copyOfCopy = List.copyOf(copy);54: var thirdCopy = new ArrayList<>(copyOfCopy);55:56: list.replaceAll(x -> x * 2);57: one.replaceAll(x -> x * 2);58: thirdCopy.replaceAll(x -> x * 2);59:60: System.out.println(thirdCopy);
The key to this question is keeping track of the types. Line 48 is a Map<Integer, Integer>. Line 49 builds a List out of a Set of Entry objects, giving us List<Entry<Integer, Integer>>. This causes a compiler error on line 56 since we can't multiply an Entry object by two. Lines 51-54 are all of type List<Integer>. The first three are immutable, and the one on line 54 is mutable. This means line 57 throws an UnsupportedOperationException since we attempt to modify the list. Line 58 would work if we could get to it. There is one compiler error and one runtime error.
Which functional interfaces complete the following code? For line 7, assume m and n are instances of functional interfaces that exist and have the same type as y. (Select the three choices that apply) 6: _________ x = String::new;7: _________ y = m.andThen(n);8: _________ z = a -> a + a;
We can eliminate four choices right away. "BinaryConsumer<String, String>" and "BinaryFunction<String, String>" are there to mislead you; these interfaces don't exist. "BiFunction<String, String>" is incorrect because a BiFunction<T,U,R> takes three generic arguments, not two. "Predicate<String>" is incorrect because none of the examples returns a boolean. The declaration on line 6 doesn't take any parameters, and it returns a String, so a Supplier<String> can fill in the blank, making "Supplier<String>" correct. The declaration on line 7 requires you to recognize that Consumer and Function, along with their binary equivalents, have an andThen() method. This makes "BiConsumer<String, String>" correct. Finally, line 8 takes a single parameter, and it returns the same type, which is a UnaryOperator. Since the types are the same, only one generic parameter is needed, making "UnaryOperator<String>" correct.
What is the result of the following program? 3: public record Sorted(int num, String text)4: implements Comparable<Sorted>, Comparator<Sorted> {5:6: public String toString() { return "" + num; }7: public int compareTo(Sorted s) {8: return text.compareTo(s.text);9: }10: public int compare(Sorted s1, Sorted s2) {11: return s1.num - s2.num;12: }13: public static void main(String[] args) {14: var s1 = new Sorted(88, "a");15: var s2 = new Sorted(55, "b");16: var t1 = new TreeSet<Sorted>();17: t1.add(s1); t1.add(s2);18: var t2 = new TreeSet<Sorted>(s1);19: t2.add(s1); t2.add(s2);20: System.out.println(t1 + " " + t2);21: } }
[88, 55] [55, 88]
What is the result of the following program? 3: public class MyComparator implements Comparator<String> {4: public int compare(String a, String b) {5: return b.toLowerCase().compareTo(a.toLowerCase());6: }7: public static void main(String[] args) {8: String[] values = { "123", "Abb", "aab" };9: Arrays.sort(values, new MyComparator());10: for (var s: values)11: System.out.print(s + " ");12: }13: }
aab Abb 123
Which of the following statements are true? (Select the three choices that apply)
compare() takes two method parameters. Comparator is in the java.util package. compare() is in the Comparator interface.
Which lambda expression, when entered into the blank line in the following code, causes the program to printhahaha? (Select the two choices that apply) import java.util.function.Predicate;public class Hyena { private int age = 1; public static void main(String[] args) { var p = new Hyena(); double height = 10; int age = 1; testLaugh(p, _________________________); age = 2; } static void testLaugh(Hyena panda, Predicate<Hyena> joke) { var r = joke.test(panda) ? "hahaha" : "silence"; System.out.print(r); }}
h -> h.age < 5 var -> p.age <= 10
Which of these statements can fill in the blank so that the Helper class compiles successfully? (Select the three choices that apply) 2: public class Helper {3: public static <U extends Exception>4: void printException(U u) {5:6: System.out.println(u.getMessage());7: }8: public static void main(String[] args) {9: Helper.____________________________________;10: } }
printException(new Exception("B")) printException(new FileNotFoundException("A")) <NullPointerException>printException(new NullPointerException ("D"))
What is the result of the following? var map = new HashMap<Integer, Integer>();map.put(1, 10);map.put(2, 20);map.put(3, null);map.merge(1, 3, (a,b) -> a + b);map.merge(3, 3, (a,b) -> a + b);System.out.println(map);
{1=13, 2=20, 3=3}