Chapter 14 is the third and final practice exam chapter in the book. Make sure you have 90 minutes and scratch paper before you start. Good luck on both this chapter and the real exam!
switch
statement may contain at most one default
statement.|
) and (||
) are interchangeable, producing the same results at runtime.!
) operator may be applied to numeric expressions.public class Legos {
public static void main(String[] args) {
var ok = true;
if (ok) {
var sb = new StringBuilder();
sb.append("red");
sb.deleteCharAt(0);
sb.delete(1, 1);
}
System.out.print(sb);
} }
r
e
ed
red
ServiceLoader<Mouse> sl = ServiceLoader.load(Mouse.class);
ServiceLoader<Mouse> sl = ServiceLoader.loader(Mouse.class);
ServiceLoader<Mouse> sl = ServiceLoader.lookup(Mouse.class);
ServiceLocator<Mouse> sl = ServiceLoader.load(Mouse.class);
ServiceLocator<Mouse> sl = ServiceLoader.loader(Mouse.class);
ServiceLocator<Mouse> sl = ServiceLoader.lookup(Mouse.class);
1: import java.util.function.*;
2: public class Ready {
3: private static double getNumber() {
4: return .007;
5: }
6: public static void main(String[] args) {
7: Supplier<double> s = Ready::getNumber;
8: double d = s.get();
9: System.out.println(d);
10: } }
0
0.007
var e = Executors.newSingleThreadExecutor();
Runnable r1 = () -> Stream.of(1,2,3).parallel();
Callable r2 = () -> Stream.of(4,5,6).parallel();
Future<Stream<Integer>> f1 = e.submit(r1); // x1
Future<Stream<Integer>> f2 = e.submit(r2); // x2
var r = Stream.of(f1.get(),f2.get())
.flatMap(p -> p) // x3
.parallelStream() // x4
.collect(
Collectors.groupingByConcurrent(i -> i%2==0));
System.out.print(r.get(false).size()
+" "+r.get(true).size());
3 3
2 4
x1
, x2
, x3
, x4
) does not compile.x1
, x2
, x3
, x4
) do not compile.x1
, x2
, x3
, x4
) do not compile.true
?
import java.util.function.*;
import java.util.stream.*;
public class HideAndSeek {
public static void main(String[] args) {
var hide = Stream.of(true, false, true);
Predicate<Boolean> pred = b -> b;
var found = hide.filter(pred)._______________________(pred);
System.out.println(found);
} }
anyMatch
allMatch
anyMatch
and allMatch
noneMatch
noneMatch
and anyMatch
lion()
method within a Lion
service. You have four distinct modules: consumer, service locator, service provider, and service provider interface. If you add a parameter to the lion()
method, how many of the modules require recompilation?
package music;
interface DoubleBass {
void strum();
default int getVolume() {return 5;}
}
interface BassGuitar {
void strum();
default int getVolume() {return 10;}
}
abstract class ElectricBass implements DoubleBass, BassGuitar {
@Override public void strum() {System.out.print("X");}
}
public class RockBand {
public static void main(String[] strings) {
final class MyElectricBass extends ElectricBass {
public int getVolume() {return 30;}
public void strum() {System.out.print("Y");}
} } }
X
Y
ElectricBass
is the first class to not compile.RockBand
is the first class to not compile.Comparable
implementation is often implemented by a lambda.Comparable
object has a compare()
method.compare()
and compareTo()
methods have the same contract for the return value.List
using different Comparator
implementations.true
for equals()
will always return 0
when passed to compareTo()
.package armory;
import java.util.function.*;
interface Shield {
void protect();
}
class Dragon {
int addDragon(Integer count) {
return ++count;
} }
public class Sword {
public static void main(String[] knight) {
var dragon = new Dragon();
Function<Shield, Sword> func = Shield::protect; // line x
UnaryOperator<Integer> op = dragon::addDragon; // line y
} }
x
y
x
and y
-p
and -cp
on the javac
command? (Choose two.)
--module-path
and -classpath
--module-path
and -class-path
--module-path
and --class-path
--path
and -classpath
--path
and -class-path
--path
and --class-path
11: public void colors() {
12: var yellow = "";
13: yellow = null;
14:
15: var red = null;
16:
17: var blue = "";
18: blue = 1;
19:
20: var var = "";
21: var = "";
22:
23: var pink = 1;
24: }
package ballroom;
public class Dance {
public static void swing(int… beats)
throws ClassCastException {
try {
System.out.print("1"+beats[2]); // p1
} catch (RuntimeException e) {
System.out.print("2");
} catch (Exception e) {
System.out.print("3");
} finally {
System.out.print("4");
} }
public static void main(String[] music) {
new Dance().swing(0,0); // p2
System.out.print("5");
} }
145
1045
24
, followed by a stack trace245
p1
.p2
.1: interface HasHue {String getHue();}
2: enum COLORS implements HasHue {
3: red {
4: public String getHue() {return "FF0000";}
5: }, green {
6: public String getHue() {return "00FF00";}
7: }, blue {
8: public String getHue() {return "0000FF";}
9: }
10: private COLORS() {}
11: }
12: class Book {
13: static void main(String[] pencils) {}
14: }
15: final public class ColoringBook extends Book {
16: final void paint(COLORS c) {
17: System.out.print("Painting: " + c.getHue());
18: }
19: final public static void main(String[] crayons) {
20: new ColoringBook().paint(green);
21: } }
Painting: 00FF00
private static void choices(PreparedStatement ps,
String sql) throws SQLException {
try (var rs = ps.executeQuery()) {
System.out.println(rs.getInt(1));
} }
private static void moreChoices(PreparedStatement ps,
String sql) throws SQLException {
try (var rs = ps.executeQuery()) {
rs.next();
System.out.println(rs.getInt(1));
} }
private static void stillMoreChoices(PreparedStatement ps,
String sql) throws SQLException {
try (var rs = ps.executeQuery()) {
if (rs.next())
System.out.println(rs.getInt(1));
}
} }
moreChoices()
stillMoreChoices()
choices()
and stillMoreChoices()
moreChoices()
and stillMoreChoices()
var localDate = LocalDate.of(2022, Month.NOVEMBER, 6);
var localTime = LocalTime.of(1, 0);
var zone = ZoneId.of("America/New_York");
var z = ZonedDateTime.of(localDate, localTime, zone);
var offset = z.getOffset();
for (int i = 0; i < 6; i++)
z = z.plusHours(1);
System.out.print(z.getHour() + " "
+ offset.equals(z.getOffset()));
5 false
5 true
6 false
6 true
7 false
7 true
Light
program?
package physics;
class Wave {
public int size = 7;
}
public class Light extends Wave {
public int size = 5;
public static void main(String… emc2) {
Light v1 = new Light();
var v2 = new Light();
Wave v3 = new Light();
System.out.println(v1.size+","+v2.size+","+v3.size);
} }
5,5,5
5,5,7
5,7,7
7,7,7
update_data
that has one IN
parameter named data
. Which fills in the blank so the code runs without error?
String sql = "{call update_data(?)}";
try (Connection conn = DriverManager.getConnection(url);
Statement cs = conn.prepareCall(sql)) {
cs.____________(1, 6);
var rs = cs.execute();
}
registerInParameter
registerIntParameter
registerInputParameter
setIn
setInt
setInteger
import java.time.LocalDate;
public class Animal {
private record Baby(String name, LocalDate birth) { }
public static void main(String[] args) {
LocalDate now = LocalDate.now();
var b1 = new Baby("Teddy", now);
var b2 = new Baby("Teddy", now);
System.out.println((b1 == b2) + " " + b1.equals(b2));
System.out.println(b1);
} }
false false
false true
true false
true true
Baby[name=Teddy, birth=2022-05-21]
Baby@1d81eb93
public void countPets() {
record Pet(int age) {}
record PetSummary(long count, int sum) {}
var summary = Stream.of(new Pet(2), new Pet(5), new Pet(8))
.collect(Collectors.teeing(
Collectors.counting(),
Collectors.summingInt(Pet::age)));
System.out.println(summary);
}
PetSummary[count=1, sum=3]
PetSummary[count=1, sum=15]
PetSummary[count=3, sum=3]
PetSummary[count=3, sum=15]
teeing()
call.First
, called Chicken
and Egg
? (Choose two.)
public sealed class First { }
Chicken
and Egg
must be classes.Chicken
and Egg
can be classes, interfaces, enums, or records.Chicken
and Egg
must be located in a file other than First
.Chicken
and Egg
must be located in the same file as First
.Chicken
and Egg
must be located as nested classes of First
.Chicken
and Egg
may be located in the same file or a different file as First
.try
/catch
blocks are correct? (Choose two.)
catch
block can never appear after a finally
block.try
block must be followed by a catch
block.finally
block can never appear after a catch
block.try
block must be followed by a finally
block.try
block can have zero or more catch
blocks.try
block can have more than one finally
block.package reptile;
public class Alligator {
static int teeth;
double scaleToughness;
public Alligator() {
this.teeth++;
}
public void snap(int teeth) {
System.out.print(teeth+" ");
teeth--;
}
public static void main(String[] unused) {
new Alligator().snap(teeth);
new Alligator().snap(teeth);
} }
0 1
1 1
1 2
2 2
String cheese = ServiceLoader.stream(Mouse.class)
.map(__________________)
.map(Mouse::favoriteFood)
.findFirst()
.orElse("");
Mouse.get()
Mouse::get
Provider.get()
Provider::get
abstract public class Exam {
boolean pass;
protected abstract boolean passed();
class JavaProgrammerCert extends Exam {
private Exam part1;
private Exam part2;
_______________________________________
}
}
boolean passed() {
return part1.pass && part2.pass;
}
boolean passed() {
return part1.passed() && part2.passed();
}
private boolean passed() {
return super.passed();
}
public boolean passed() {
return part1.passed() && part2.passed();
}
public boolean passed() {
return part1.pass && part2.pass;
}
public boolean passed() {
return super.passed();
}
false
?
23: var smart = """
24: barn owl
25: wise
26: """;
27: var clever = """
28: barn owl
29: wise
30: """;
31: var sly = """
32: barn owl
33: wise""";
34:
35: System.out.println(smart.equals(smart.indent(0)));
36: System.out.println(smart.equals(smart.strip()));
37: System.out.println(smart.equals(smart.stripIndent()));
38:
39: System.out.println(clever.equals(clever.indent(0)));
40: System.out.println(clever.equals(clever.strip()));
41: System.out.println(clever.equals(clever.stripIndent()));
42:
43: System.out.println(sly.equals(sly.indent(0)));
44: System.out.println(sly.equals(sly.strip()));
45: System.out.println(sly.equals(sly.stripIndent()));
public
, while interfaces can use various access modifiers for their methods and variables, including private
in some cases.abstract
methods.public
constructors.final
.+=
, ______, ______, _______, _______, and --
are listed in increasing or the same level of operator precedence. (Choose two.)
^
, *
, =
, ++
%
, *
, /
, &&
=
, +
, /
, *
^
, *
, ==
, ++
*
, /
, %
, ++<=
, >=
, !=
, !
public class Big {
public Big(boolean stillIn) {
super();
} }
public class Trouble extends Big {
public Trouble() {}
public Trouble(int deep) {
super(false);
this();
}
public Trouble(String now, int… deep) {
this(3);
}
public Trouble(long deep) {
this("check", deep);
}
public Trouble(double test) {
super(test>5 ? true : false);
} }
public Big(boolean stillIn)
public Trouble()
public Trouble(int deep)
public Trouble(String now, int… deep)
public Trouble(long deep)
public Trouble(double test)
11: Path x = Paths.get(".","song","..","/note");
12: Path y = Paths.get("/dance/move.txt");
13: x.normalize();
14: System.out.println(x.resolve(y));
15: System.out.println(y.resolve(x));
/./song/../note/dance/move.txt
/dance/move.txt
/dance/move.txt
/dance/move.txt/note
/dance/move.txt
/dance/move.txt/./song/../note
/note/dance/move.txt
../dance/move.txt/song
import java.util.*;
public class PrintNegative {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(-5);
list.add(0);
list.add(5);
list.removeIf(e -> e < 0);
list.forEach(x -> System.out.println(x));
} }
public static void main(String[] args) {
var list = Arrays.asList("0", "1", "01", "10");
Collections.reverse(list);
Collections.sort(list);
System.out.println(list);
}
[]
[0, 01, 1, 10]
[0, 01, 10, 1]
[0, 1, 01, 10]
var dice = new TreeSet<Integer>();
dice.add(6);
dice.add(6);
dice.add(4);
dice.stream()
.filter(n -> n != 4)
.forEach(System.out::println)
.count();
3
.main()
method?
package store;
public class Shoes {
static String shoe1 = new String("sandal");
static String shoe2 = new String("flip flop");
public void shopping() {
String shoe3 = new String("croc");
shoe2 = shoe1;
shoe1 = shoe3;
}
public static void main(String… args) {
new Shoes().shopping();
} }
20: int[] crossword [] = new int[10][20];
21: for (int i = 0; i < crossword.length; i++)
22: for (int j = 0; j < crossword.length; j++)
23: crossword[i][j] = 'x';
24: System.out.println(crossword.size());
0
.0
.0
.sea lion, bald eagle
?
String names = Stream.of(
"bald eagle", "pronghorn", "puma", "sea lion")
____________________
.collect(Collectors.joining(", "));
System.out.println(names);
.filter(s -> s.contains(" "))
.collect(Collectors.toSet())
.stream()
.entrySet()
.stream()
.filter(e -> e.getKey())
.map(Entry::getValue)
.flatMap(List::stream)
.sorted(Comparator.reverseOrder())
.filter(s -> s.contains(" "))
.collect(Collectors.toUnmodifiableSet())
.stream()
.entrySet()
.stream()
.filter(e -> e.getKey())
.map(Entry::getValue)
.flatMap(List::stream)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toUnmodifiableSet())
.stream()
.collect(Collectors.groupingBy(s -> s.contains(" ")))
.entrySet()
.stream()
.filter(e -> e.getKey())
.map(Entry::getValue)
.map(List::stream)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toSet())
.stream()
.collect(Collectors.groupingBy(s -> s.contains(" ")))
.entrySet()
.stream()
.filter(e -> e.getKey())
.map(Entry::getValue)
.flatMap(List::stream)
.sorted(Comparator.reverseOrder())
.filter(s -> s.contains(" "))
.collect(Collectors.toUnmodifiableSet())
.stream()
.collect(Collectors.groupingBy(s -> s.contains(" ")))
.entrySet()
.stream()
.filter(e -> e.getKey())
.map(Entry::getValue)
.map(List::stream)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toUnmodifiableSet())
.stream()
.collect(Collectors.groupingBy(s -> s.contains(" ")))
.entrySet()
.stream()
.filter(e -> e.getKey())
.map(Entry::getValue)
.map(List::stream)
.sorted(Comparator.reverseOrder())
LocalDate dogDay = LocalDate.of(2022,8,26);
var x = DateTimeFormatter.ISO_DATE;
System.out.println(x.format(dogDay));
var y = DateTimeFormatter.ofPattern("Dog Day: dd/MM/yy");
System.out.println(y.format(dogDay));
var z = DateTimeFormatter.ofPattern("Dog Day: dd/MM/yy");
System.out.println(dogDay.format(z));
2022-07-26
and Dog Day: 26/07/22
2022-07-25
and Dog Day: 25/07/22
2022-08-26
and Dog Day: 26/08/22
long min1 = 123.0, max1 = 987L;
final long min2 = 1_2_3, max2 = 9 ____________ 8 ____________ 7;
long min3 = 123, int max3 = 987;
long min4 = 123L, max4 = 987;
long min5 = 123_, max5 = _987;
class
, static
default
, public
final
, package (no modifier)protected
, instance
public
, static
-1 0 2
?
char[][] letters = new char[][] {
new char[] { 'a', 'e', 'i', 'o', 'u'},
new char[] { 'a', 'e', 'o', 'u'} };
var x = Arrays.____________(letters[0], letters[0]);
var y = Arrays.____________(letters[0], letters[0]);
var z = Arrays.____________(letters[0], letters[1]);
System.out.print(x + " " + y + " " + z);
compare
, mismatch
, compare
compare
, mismatch
, mismatch
mismatch
, compare
, compare
mismatch
, compare
, mismatch
package boat;
import java.io.*;
public class Cruise {
private int numPassengers = 1;
private transient String schedule = "NONE";
{ numPassengers = 2; }
public Cruise() {
this.numPassengers = 3;
this.schedule = "Tropical Island";
}
public static void main(String… p) throws Exception {
final String f = "ship.txt";
try (var o = new ObjectOutputStream(
new FileOutputStream(f))) {
Cruise c = new Cruise();
c.numPassengers = 4;
c.schedule = "Casino";
o.writeObject(c);
}
try (var i = new ObjectInputStream(
new FileInputStream(f))) {
Cruise c = i.readObject();
System.out.print(c.numPassengers + "," + c.schedule);
} } }
2,NONE
3,null
4,Casino
4,null
class Coin {
enum Side { HEADS, TAILS };
public static void main(String[] args) {
var sides = Side.values();
for (var s : sides)
for (int i=sides.length; i>0 ; i-=2)
System.out.print(s+" "+sides[i]);
System.out.println();
}
}
@FunctionalInterface
public interface Play {
public static void baseball() {}
private static void soccer() {}
default void play() {}
void fun();
void game();
void toy();
}
10: var m = new TreeMap<Integer, Integer>();
11: m.put(1, 4);
12: m.put(2, 8);
13:
14: m.putIfAbsent(2, 10);
15: m.putIfAbsent(3, 9);
16:
17: m.replaceAll((k, v) -> k + 1);
18:
19: m.entrySet().stream()
20: .sorted(Comparator.comparing(Entry::getKey))
21: .limit(1)
22: .map(Entry::getValue)
23: .forEach(System.out::println);
1
2
3
4
toothbrush.properties
color=purple
type=generic
toothbrush_es.properties
color=morado
type=lujoso
toothbrush_fr.properties
color=violette
void brush() {
Locale.setDefault(new Locale.Builder()
.setLanguage("es")
.setRegion("MX").build());
var rb = ResourceBundle.getBundle("toothbrush",
new Locale("fr"));
var a = rb.getString("color");
var b = rb.getString("type");
System.out.print(a + " " + b);
}
morado null
violette generic
morado lujoso
violette null
import java.io.*;
class Music {
void make() throws IOException {
throw new UnsupportedOperationException();
} }
public class Sing extends Music {
public void make() _____________________ {
System.out.println("do-re-mi-fa-so-la-ti-do");
} }
throws FileNotFoundException
throws NumberFormatException
throws Exception
throws SQLException
throws Throwable
package furryfriends;
interface Friend {
protected String getName(); // h1
}
class Cat implements Friend {
String getName() { // h2
return "Kitty";
} }
public class Dog implements Friend {
String getName() throws RuntimeException { // h3
return "Doggy";
}
public static void main(String[] adoption) {
Friend friend = new Dog(); // h4
System.out.print(((Cat)friend).getName()); // h5
System.out.print(((Dog)null).getName()); // h6
} }
h1
h2
h3
h4
h5
h6
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: } }
2-2
200-1
500-0
500-2
module-info
file.
13.59.103.67