1.How many of the following lines contain a compiler error?
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;
A) Three
2.What is the minimum number of lines that need to be changed or
removed to make this method compile?
public void colors() {
var yellow = “”;
yellow = null;
var red = null;
var blue = “”;
blue = 1;
var var = “”;
var = “”;
var pink = 1;
}
A) Two
3.How many objects are eligible for garbage collection at the end of the
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();
} }
A) Two
4.Fill in the blanks: The operators +=, , , , , and — are
listed in increasing or the same level of operator precedence.
Each correct answer represents a complete solution. Choose all that apply.
A) =, +, /, *
*, /, %, ++
5.Which of the following are true about Java operators and statements?
Each correct answer represents a complete solution. Choose all that apply
A) A switch statement may contain at most one default statement.
B) The post-increment operator (++) returns the value of the variable
before the addition is applied.
C) An assignment operator returns a value that is equal to the value of the
expression being assigned.
6.What is the output of the following?
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);
} }
A) The code does not compile.
7.How many of these lines print false?
var smart = “””
barn owl
wise
“””;
var clever = “””
barn owl
wise
“””;
var sly = “””
barn owl
wise”””;
System.out.println(smart.equals(smart.indent(0)));
System.out.println(smart.equals(smart.strip()));
System.out.println(smart.equals(smart.stripIndent()));
System.out.println(clever.equals(clever.indent(0)));
System.out.println(clever.equals(clever.strip()));
System.out.println(clever.equals(clever.stripIndent()));
System.out.println(sly.equals(sly.indent(0)));
System.out.println(sly.equals(sly.strip()));
System.out.println(sly.equals(sly.stripIndent()));
A) Three
8.Which of the following sequences can fill in the blanks so the code
prints -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);
A) mismatch, compare, mismatch
9.In most of the United States, daylight saving time ends on November 6
at 00 and we repeat that hour. What is the output of the following?
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()));
A) 6 false
10.Fill in the blanks: Using and together allows a
variable to be accessed from any class, without requiring an instance
variable.
A) public, static
11.What is the result of compiling and executing the following code?
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);
} }
A) 1 2
12.Given the following two classes in the same package, which
constructors contain compiler errors?
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);
} }
Each correct answer represents a complete solution. Choose all that apply.
A) public Trouble()
B) public Trouble(int deep)
C) public Trouble(long deep)
13.What is the output of the 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);
} }
A) 5,5,7
14.Which lines can fill in the blank that would allow the code to
compile?
abstract public class Exam {
boolean pass;
protected abstract boolean passed();
class JavaProgrammerCert extends Exam {
private Exam part1;
private Exam part2;
A) public boolean passed() { return part1.passed() && part2.passed();}
B) public boolean passed() { return part1.pass && part2.pass;}
15.What is the output of the following code?
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”);}
} } }
A) ElectricBass is the first class to not compile.
16.Which are true statements about interfaces and abstract classes?
Each correct answer represents a complete solution. Choose all that apply.
A) Abstract classes offer support for single inheritance, while interfaces
offer support for multiple inheritance.
B) Both abstract classes and interfaces can have abstract methods
C) Interfaces can only extend other interfaces, while abstract classes can
extend both abstract and concrete classes.
17.What is the output of the following code?
interface HasHue {String getHue();}
enum COLORS implements HasHue {
red {
public String getHue() {return “FF0000”;}
}, green {
public String getHue() {return “00FF00”;}
}, blue {
public String getHue() {return “0000FF”;}
}
private COLORS() {}
}
class Book {
static void main(String[] pencils) {}
}
final public class ColoringBook extends Book {
final void paint(COLORS c) {
System.out.print(“Painting: ” + c.getHue());
}
final public static void main(String[] crayons) {
new ColoringBook().paint(green);
} }
A) Exactly two lines of code do not compile.
18.Given the following, what can we infer about subtypes of First,
called Chicken and Egg?
public sealed class First { }
Each correct answer represents a complete solution. Choose all that apply.
A) Chicken and Egg must be classes.
B) Chicken and Egg must be located in the same file as First.
19.What are possible outputs of this code?
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);
} }
Each correct answer represents a part of the solution. Choose all that apply.
A) false true
B) Baby[name=Teddy, birth=2022-05-21]
20.What is the minimum number of lines that need to be removed to
make this code compile and be able to be implemented as a lambda
expression?
@FunctionalInterface
public interface Play {
public static void baseball() {}
private static void soccer() {}
default void play() {}
void fun();
void game();
void toy();
}
A) 2
21.Which lines fail to compile?
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 func = Shield::protect; // line x
UnaryOperator op = dragon::addDragon; // line y
} }
A) Only line x
22.Which of the following are true?
int[] crossword [] = new int[10][20];
for (int i = 0; i < crossword.length; i++)
for (int j = 0; j < crossword.length; j++)
crossword[i][j] = ‘x’;
System.out.println(crossword.size());
Each correct answer represents a complete solution. Choose all that apply.
A) One line needs to be changed for this code to compile.
B) If the code is fixed to compile, half of the cells in the 2D array
have a value of 0.
23.How many lines does the following program output?
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();
}
}
A) The code compiles but throws an exception at runtime.
24.How many lines does this code output?
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));
} }
A) Two
25.What is the result of the following?
public static void main(String[] args) {
var list = Arrays.asList(“0”, “1”, “01”, “10”);
Collections.reverse(list);
Collections.sort(list);
System.out.println(list);
}
A) [0, 01, 1, 10]
26.Which statements are correct?
Each correct answer represents a complete solution. Choose all that apply.
A) The compare() and compareTo() methods have the same
contract for the return value
B) It is possible to sort the same List using different Comparator
implementations.
27.What is the result of the following?
import java.util.function.*;
public class Ready {
private static double getNumber() {
return .007;
}
public static void main(String[] args) {
Supplier s = Ready::getNumber;
double d = s.get();
System.out.println(d);
} }
A) The code does not compile due to line 7.
28.What is the output of this code?
1. var m = new TreeMap<Integer,Integer>();
2.m.put(1, 4);
3.m.put(2, 8);
4.
5.m.putIfAbsent(2, 10);
6.m.putIfAbsent(3, 9);
7.
8.m.replaceAll((k, v) -> k + 1);
9.
10.m.entrySet().stream()
11..sorted(Comparator.comparing(Entry::getKey))
12.limit(1)
13.map(Entry::getValue)
14.forEach(System.out::println);
A) 2
29.What is the result of the following code snippet?
var dice = new TreeSet();
dice.add(6);
dice.add(6);
dice.add(4);
dice.stream()
.filter(n -> n != 4)
.forEach(System.out::println)
.count();
A) The code does not compile.
30.30.Which can fill in the blank so this code outputs 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 pred = b -> b;
var found = hide.filter(pred).___________(pred);
System.out.println(found);
} }
A) Both anyMatch and allMatch
31.What is the output of the following code?
package reader;
import java.util.stream.*;
public class Books {
public static void main(String[] args) {
IntStream pages = IntStream.of(200, 300);
long total = pages.sum();
long count = pages.count();
System.out.println(total + “-” + count);
} }
A) The code compiles but throws an exception at runtime.
32.Which of the following can fill in the blank to output sea lion, bald
eagle?
String names = Stream.of(
“bald eagle”, “pronghorn”, “puma”, “sea lion”)
.collect(Collectors.joining(“, “));
System.out.println(names);
A) collect(Collectors.toSet()).stream().collect(Collectors.groupingBy(s -> s.c
ontains(” “))).entrySet().stream().filter(e -> e.getKey()).map(Entry::getValu
e).flatMap(List::stream).sorted(Comparator.reverseOrder())
33.What is the output of calling the following method?
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);
}
A) The code does not compile due to the teeing() call.
34.Given the application shown here, which lines do not compile?
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
} }
Each correct answer represents a complete solution. Choose all that apply.
A) Line h1
B) Line h2
C) Line h3
35.Which options, when inserted into the blank, allow this code to compile?
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”);
} }
Each correct answer represents a complete solution. Choose all that apply.
A) throws FileNotFoundException
B) throws NumberFormatException
C) Placing nothing in the blank
36.Which of the following statements about try/catch blocks are correct?
Each correct answer represents a complete solution. Choose all that apply.
A) A catch block can never appear after a finally block.
B) A try block can have zero or more catch blocks.
37.What is the output of the following code?
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”);
} }
A) 245
38.What is the output of the following code snippet?
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));
A) An exception is thrown at runtime.
39.Given the following three property files, what does the following method
output?
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);
A) violette generic
40.What option names are equivalent to -p and -cp on the javac command?
Each correct answer represents a complete solution. Choose all that apply.
A) –module-path and -classpath
B) –module-path and –class-path
41.Fill in the blank to make this code compile:
String cheese = ServiceLoader.stream(Mouse.class)
.map(______)
.map(Mouse::favoriteFood)
.findFirst()
.orElse(“”);
A) None of these
42.Suppose you have a consumer that calls the 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?
A) Three
43.Which line of code belongs in a service locator?
A) ServiceLoader<Mouse> sl = ServiceLoader.load(Mouse.class);
44.___ modules are on the classpath, while __
modules never contain a module-info file
A) Unnamed, automatic
45.Which condition is most likely to result in invalid data entering the
system?
A) Race condition
46.What is the output of executing the following code snippet?
var e = Executors.newSingleThreadExecutor();
Runnable r1 = () -> Stream.of(1,2,3).parallel();
Callable r2 = () -> Stream.of(4,5,6).parallel();
Future<Streem<Integer>> f1 = e.submit(r1); // x1
Future<Streem<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());
A) Two of the marked lines (x1, x2, x3, x4) do not compile.
47.What is the output of the following code snippet?
Path x = Paths.get(“.”,”song”,”..”,”/note”);
Path y = Paths.get(“/dance/move.txt”);
x.normalize();
System.out.println(x.resolve(y));
System.out.println(y.resolve(x));
A) /dance/move.txt/dance/move.txt/./song/../note
48.What is the output of the following application? Assume the file system
is available and able to be written to and read from
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);
} } }
A) Two lines would need to be fixed for this code to run without
throwing an exception
49.Which of the following methods can run without error for a SQL query
that returns a count of matching rows?
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));
}
} }
A) moreChoices() and stillMoreChoices()
50.Suppose we have a stored procedure named 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();
}
A) None of these
Other Links:
Statistics Quiz
Networking Quiz
See other websites for quiz:
Check on QUIZLET
Check on CHEGG
