Module 1 Flashcards

1
Q

Which of the following are valid Java identifiers? (Choose all that apply)
A. A$B
B. _helloWorld
C. true
D. java.lang
E. Public
F. 1980_s

A

A, B, E

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

What is the output of the following program?
1: public class WaterBottle {
2: private String brand;
3: private boolean empty;
4: public static void main(String[] args) {
5: WaterBottle wb = new WaterBottle();
6: System.out.print(“Empty = “ + wb.empty);
7: System.out.print(“, Brand = “ + wb.brand);
8: } }
A. Line 6 generates a compiler error.
B. Line 7 generates a compiler error.
C. There is no output.
D. Empty = false, Brand = null
E. Empty = false, Brand =
F. Empty = null, Brand = null

A

D. Boolean fields initialize to false and references initialize to null, so empty is false
and brand is null. Brand = null is output.

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

Which of the following are true? (Choose all that apply)
4: short numPets = 5;
5: int numGrains = 5.6;
6: String name = “Scruffy”;
7: numPets.length();
8: numGrains.length();
9: name.length();
A. Line 4 generates a compiler error.
B. Line 5 generates a compiler error.
C. Line 6 generates a compiler error.
D. Line 7 generates a compiler error.
E. Line 8 generates a compiler error.
F. Line 9 generates a compiler error.
G. The code compiles as is

A

B, D, E. Option A (line 4) compiles because short is an integral type. Option B (line
5) generates a compiler error because int is an integral type, but 5.6 is a floating-point
type. Option C (line 6) compiles because it is assigned a String. Options D and E (lines
7 and 8) do not compile because short and int are primitives. Primitives do not allow
methods to be called on them. Option F (line 9) compiles because length() is defined
on String

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

Given the following class, which of the following is true? (Choose all that apply)
1: public class Snake {
2:
3: public void shed(boolean time) {
4:
5: if (time) {
6:
7: }
8: System.out.println(result);
9:
10: }
11: }
A. If String result = “done”; is inserted on line 2, the code will compile.
B. If String result = “done”; is inserted on line 4, the code will compile.
C. If String result = “done”; is inserted on line 6, the code will compile.
D. If String result = “done”; is inserted on line 9, the code will compile.
E. None of the above changes will make the code compile.

A

A, B. Adding the variable at line 2 makes result an instance variable. Since instance
variables are in scope for the entire life of the object, option A is correct. Option B is
correct because adding the variable at line 4 makes result a local variable with a scope
of the whole method. Adding the variable at line 6 makes result a local variable with
a scope of lines 6–7. Since it is out of scope on line 8, the println does not compile and
option C is incorrect. Adding the variable at line 9 makes result a local variable with
a scope of lines 9 and 10. Since line 8 is before the declaration, it does not compile and
option D is incorrect. Finally, option E is incorrect because the code can be made to
compile

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

Given the following classes, which of the following can independently replace INSERT
IMPORTS HERE to make the code compile? (Choose all that apply)
package aquarium;
public class Tank { }
package aquarium.jellies;
public class Jelly { }
package visitor;
INSERT IMPORTS HERE
public class AquariumVisitor {
public void admire(Jelly jelly) { } }
A. import aquarium.;
B. import aquarium.
.Jelly;
C. import aquarium.jellies.Jelly;
D. import aquarium.jellies.;
E. import aquarium.jellies.Jelly.
;
F. None of these can make the code compile.

A

C, D. Option C is correct because it imports Jelly by classname. Option D is correct because it imports all the classes in the jellies package, which includes Jelly.
Option A is incorrect because it only imports classes in the aquarium package—Tank
in this case—and not those in lower-level packages. Option B is incorrect because you
cannot use wildcards anyplace other than the end of an import statement. Option E is
incorrect because you cannot import parts of a class with a regular import statement.
Option F is incorrect because options C and D do make the code compile.

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

Given the following classes, what is the maximum number of imports that can be removed
and have the code still compile?
package aquarium; public class Water { }
package aquarium;
import java.lang.;
import java.lang.System;
import aquarium.Water;
import aquarium.
;
public class Tank {
public void print(Water water) {
System.out.println(water); } }
A. 0
B. 1
C. 2
D. 3
E. 4
F. Does not compile.

A

E. The first two imports can be removed because java.lang is automatically imported.
The second two imports can be removed because Tank and Water are in the same package, making the correct answer E. If Tank and Water were in different packages, one of
these two imports could be removed. In that case, the answer would be option D.

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

Given the following classes, which of the following snippets can be inserted in place of
INSERT IMPORTS HERE and have the code compile? (Choose all that apply)
package aquarium;
public class Water {
boolean salty = false;
}
package aquarium.jellies;
public class Water {
boolean salty = true;
}
package employee;
INSERT IMPORTS HERE
public class WaterFiller {
Water water;
}
A. import aquarium.;
B. import aquarium.Water;
import aquarium.jellies.
;
C. import aquarium.;
import aquarium.jellies.Water;
D. import aquarium.
;
import aquarium.jellies.*;
E. import aquarium.Water;
import aquarium.jellies.Water;
F. None of these imports can make the code compile.

A

A, B, C. Option A is correct because it imports all the classes in the aquarium package
including aquarium.Water. Options B and C are correct because they import Water by
classname. Since importing by classname takes precedence over wildcards, these compile. Option D is incorrect because Java doesn’t know which of the two wildcard Water classes to use. Option E is incorrect because you cannot specify the same classname in
two imports.

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

Given the following class, which of the following calls print out Blue Jay? (Choose all that
apply)
public class BirdDisplay {
public static void main(String[] name) {
System.out.println(name[1]);
} }
A. java BirdDisplay Sparrow Blue Jay
B. java BirdDisplay Sparrow “Blue Jay”
C. java BirdDisplay Blue Jay Sparrow
D. java BirdDisplay “Blue Jay” Sparrow
E. java BirdDisplay.class Sparrow “Blue Jay”
F. java BirdDisplay.class “Blue Jay” Sparrow
G. Does not compile

A

B. Option B is correct because arrays start counting from zero and strings with spaces
must be in quotes. Option A is incorrect because it outputs Blue. C is incorrect because
it outputs Jay. Option D is incorrect because it outputs Sparrow. Options E and F are
incorrect because they output Error: Could not find or load main class BirdDisplay.class.

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

Which of the following legally fill in the blank so you can run the main() method from the
command line? (Choose all that apply)
public static void main( )
A. String[] _names
B. String[] 123
C. String abc[]
D. String _Names[]
E. String… $n
F. String names
G. None of the above.

A

A, C, D, E. Option A is correct because it is the traditional main() method signature
and variables may begin with underscores. Options C and D are correct because the
array operator may appear after the variable name. Option E is correct because
varargs are allowed in place of an array. Option B is incorrect because variables are
not allowed to begin with a digit. Option F is incorrect because the argument must be
an array or varargs. Option F is a perfectly good method. However, it is not one that
can be run from the command line because it has the wrong parameter type

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

Which of the following are legal entry point methods that can be run from the command
line? (Choose all that apply)
A. private static void main(String[] args)
B. public static final main(String[] args)
C. public void main(String[] args)
D. public static void test(String[] args)
E. public static void main(String[] args)
F. public static main(String[] args)
G. None of the above.

A

E. Option E is the canonical main() method signature. You need to memorize it.
Option A is incorrect because the main() method must be public. Options B and F
are incorrect because the main() method must have a void return type. Option C is
incorrect because the main() method must be static. Option D is incorrect because the
main() method must be named main.

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

Which of the following are true? (Choose all that apply)
A. An instance variable of type double defaults to null.
B. An instance variable of type int defaults to null.
C. An instance variable of type String defaults to null.
D. An instance variable of type double defaults to 0.0.
E. An instance variable of type int defaults to 0.0.
F. An instance variable of type String defaults to 0.0.
G. None of the above.

A

C, D. Option C is correct because all non-primitive values default to null. Option D is
correct because float and double primitives default to 0.0. Options B and E are incorrect because int primitives default to 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
  1. Which of the following are true? (Choose all that apply)
    A. A local variable of type boolean defaults to null.
    B. A local variable of type float defaults to 0.
    C. A local variable of type Object defaults to null.
    D. A local variable of type boolean defaults to false.
    E. A local variable of type boolean defaults to true.
    F. A local variable of type float defaults to 0.0.
    G. None of the above
A

G. Option G is correct because local variables do not get assigned default values. The
code fails to compile if a local variable is not explicitly initialized. If this question
were about instance variables, options D and F would be correct. A boolean primitive
defaults to false and a float primitive defaults to 0.0.

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

Which of the following are true? (Choose all that apply)
A. An instance variable of type boolean defaults to false.
B. An instance variable of type boolean defaults to true.
C. An instance variable of type boolean defaults to null.
D. An instance variable of type int defaults to 0.
E. An instance variable of type int defaults to 0.0.
F. An instance variable of type int defaults to null.
G. None of the above.

A

A, D. Options A and D are correct because boolean primitives default to false and
int primitives default to 0.

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

Given the following class in the file /my/directory/named/A/Bird.java:
INSERT CODE HERE
public class Bird { }
Which of the following replaces INSERT CODE HERE if we compile from /my/directory?
(Choose all that apply)
A. package my.directory.named.a;
B. package my.directory.named.A;
C. package named.a;
D. package named.A;
E. package a;
F. package A;
G. Does not compile.

A

D. The package name represents any folders underneath the current path, which is
named.A in this case. Option B is incorrect because package names are case sensitive,
just like variable names and other identifiers.

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

Which of the following lines of code compile? (Choose all that apply)
A. int i1 = 1_234;
B. double d1 = 1234.0;
C. double d2 = 1_234._0;
D. double d3 = 1234.0;
E. double d4 = 1_234.0;
F. None of the above.

A

A, E. Underscores are allowed as long as they are directly between two other digits.
This means options A and E are correct. Options B and C are incorrect because the
underscore is adjacent to the decimal point. Option D is incorrect because the underscore is the last character.

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

Given the following class, which of the following lines of code can replace INSERT CODE
HERE to make the code compile? (Choose all that apply)
public class Price {
public void admission() {
INSERT CODE HERE
System.out.println(amount);
} }
A. int amount = 9L;
B. int amount = 0b101;
C. int amount = 0xE;
D. double amount = 0xE;
E. double amount = 12.0_0;
F. int amount = 12;
G. None of the above.

A

B, C, D. 0b is the prefix for a binary value and is correct. 0x is the prefix for a hexadecimal value. This value can be assigned to many primitive types, including int and
double, making options C and D correct. Option A is incorrect because 9L is a long
value. long amount = 9L would be allowed. Option E is incorrect because the underscore is immediately before the decimal. Option F is incorrect because the underscore is
the very last character.

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

Which of the following are true? (Choose all that apply)
public class Bunny {
public static void main(String[] args) {
Bunny bun = new Bunny();
} }
A. Bunny is a class.
B. bun is a class.
C. main is a class.
D. Bunny is a reference to an object.
E. bun is a reference to an object.
F. main is a reference to an object.
G. None of the above.

A

A, E. Bunny is a class, which can be seen from the declaration: public class Bunny. bun
is a reference to an object. main() is a method.

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

Which represent the order in which the following statements can be assembled into a program that will compile successfully? (Choose all that apply)
A: class Rabbit {}
B: import java.util.*;
C: package animals;
A. A, B, C
B. B, C, A
C. C, B, A
D. B, A
E. C, A
F. A, C
G. A, B

A

C, D, E. package and import are both optional. If both are present, the order must
be package, then import, then class. Option A is incorrect because class is before
package and import. Option B is incorrect because import is before package. Option
F is incorrect because class is before package. Option G is incorrect because class is
before import.

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

Suppose we have a class named Rabbit. Which of the following statements are true?
(Choose all that apply)
1: public class Rabbit {
2: public static void main(String[] args) {
3: Rabbit one = new Rabbit();
4: Rabbit two = new Rabbit();
5: Rabbit three = one;
6: one = null;
7: Rabbit four = one;
8: three = null;
9: two = null;
10: two = new Rabbit();
11: System.gc();
12: } }
A. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 6.
B. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 8.
C. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 12.
D. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 9.
E. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 11.
F. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 12.

A

B, D. The Rabbit object from line 3 has two references to it: one and three. The references are nulled out on lines 6 and 8, respectively. Option B is correct because this
makes the object eligible for garbage collection after line 8. Line 7 sets the reference
four to the now null one, which means it has no effect on garbage collection. The Rabbit object from line 4 only has a single reference to it: two. Option D is correct because
this single reference becomes null on line 9. The Rabbit object declared on line 10
becomes eligible for garbage collection at the end of the method on line 12. Calling
System.gc() has no effect on eligibility for garbage collection.

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

What is true about the following code? (Choose all that apply)
public class Bear {
protected void finalize() {
System.out.println(“Roar!”);
}
public static void main(String[] args) {
Bear bear = new Bear();
bear = null;
System.gc();
} }
A. finalize() is guaranteed to be called.
B. finalize() might or might not be called
C. finalize() is guaranteed not to be called.
D. Garbage collection is guaranteed to run.
E. Garbage collection might or might not run.
F. Garbage collection is guaranteed not to run.
G. The code does not compile.

A

B, E. Calling System.gc() suggests that Java might wish to run the garbage collector.
Java is free to ignore the request, making option E correct. finalize() runs if an object
attempts to be garbage collected, making option B correct.

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

What does the following code output?
1: public class Salmon {
2: int count;
3: public void Salmon() {
4: count = 4;
5: }
6: public static void main(String[] args) {
7: Salmon s = new Salmon();
8: System.out.println(s.count);
9: } }
A. 0
B. 4
C. Compilation fails on line 3.
D. Compilation fails on line 4.
E. Compilation fails on line 7.
F. Compilation fails on line 8.

A

A. While the code on line 3 does compile, it is not a constructor because it has a return
type. It is a method that happens to have the same name as the class. When the code
runs, the default constructor is called and count has the default value (0) for an int.

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

Which of the following are true statements? (Choose all that apply)
A. Java allows operator overloading.
B. Java code compiled on Windows can run on Linux.
C. Java has pointers to specific locations in memory.
D. Java is a procedural language.
E. Java is an object-oriented language.
F. Java is a functional programming language.

A

B, E. C++ has operator overloading and pointers. Java made a point of not having
either. Java does have references to objects, but these are pointing to an object that can
move around in memory. Option B is correct because Java is platform independent.
Option E is correct because Java is object oriented. While it does support some parts of
functional programming, these occur within a class.

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

Which of the following are true? (Choose all that apply)
A. javac compiles a .class file into a .java file.
B. javac compiles a .java file into a .bytecode file.
C. javac compiles a .java file into a .class file.
D. Java takes the name of the class as a parameter.
E. Java takes the name of the .bytecode file as a parameter.
F. Java takes the name of the .class file as a parameter.

A

C, D. Java puts source code in .java files and bytecode in .class files. It does not use
a .bytecode file. When running a Java program, you pass just the name of the class
without the .class extension.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
  1. Which of the following Java operators can be used with boolean variables? (Choose all that
    apply)
    A. ==
    B. +
    C. –
    D. !
    E. %
    F. <=
A

A, D. Option A is the equality operator and can be used on numeric primitives, boolean values, and object references. Options B and C are both arithmetic operators and
cannot be applied to a boolean value. Option D is the logical complement operator
and is used exclusively with boolean values. Option E is the modulus operator, which
can only be used with numeric primitives. Finally, option F is a relational operator that
compares the values of two numbers

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

What data type (or types) will allow the following code snippet to compile? (Choose all that
apply)
byte x = 5;
byte y = 10;
_____ z = x + y;
A. int
B. long
C. boolean
D. double
E. short
F. byte

A

A, B, D. The value x + y is automatically promoted to int, so int and data types that
can be promoted automatically from int will work. Options A, B, D are such data
types. Option C will not work because boolean is not a numeric data type. Options E
and F will not work without an explicit cast to a smaller data type.

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

What is the output of the following application?
1: public class CompareValues {
2: public static void main(String[] args) {
3: int x = 0;
4: while(x++ < 10) {}
5: String message = x > 10 ? “Greater than” : false;
6: System.out.println(message+”,”+x);
7: }
8: }
A. Greater than,10
B. false,10
C. Greater than,11
D. false,11
E. The code will not compile because of line 4.
F. The code will not compile because of line 5.

A

F. In this example, the ternary operator has two expressions, one of them a String and
the other a boolean value. The ternary operator is permitted to have expressions that
don’t have matching types, but the key here is the assignment to the String reference.
The compiler knows how to assign the first expression value as a String, but the second boolean expression cannot be set as a String; therefore, this line will not compile.

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

What change would allow the following code snippet to compile? (Choose all that apply)
3: long x = 10;
4: int y = 2 * x;
A. No change; it compiles as is.
B. Cast x on line 4 to int.
C. Change the data type of x on line 3 to short.
D. Cast 2 * x on line 4 to int.
E. Change the data type of y on line 4 to short.
F. Change the data type of y on line 4 to long.

A

B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x
is automatically promoted to long and cannot be automatically stored in y, which is
in an int value. Options B, C, and D solve this problem by reducing the long value to
int. Option E does not solve the problem and actually makes it worse by attempting
to place the value in a smaller data type. Option F solves the problem by increasing the
data type of the assignment so that long is allowed.

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

What is the output of the following code snippet?
3: java.util.List<Integer> list = new java.util.ArrayList<Integer>();
4: list.add(10);
5: list.add(14);
6: for(int x : list) {
7: System.out.print(x + ", ");
8: break;
9: }
A. 10, 14,
B. 10, 14
C. 10,
D. The code will not compile because of line 7.
E. The code will not compile because of line 8.
F. The code contains an infinite loop and does not terminate</Integer></Integer>

A

C. This code does not contain any compilation errors or an infinite loop, so options D,
E, and F are incorrect. The break statement on line 8 causes the loop to execute once
and finish, so option C is the correct answer.

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

What is the output of the following code snippet?
3: int x = 4;
4: long y = x * 4 - x++;
5: if(y<10) System.out.println(“Too Low”);
6: else System.out.println(“Just right”);
7: else System.out.println(“Too High”);
A. Too Low
B. Just Right
C. Too High
D. Compiles but throws a NullPointerException.
E. The code will not compile because of line 6.
F. The code will not compile because of line 7.

A

F. The code does not compile because two else statements cannot be chained together
without additional if-then statements, so the correct answer is option F. Option E is
incorrect as Line 6 by itself does not cause a problem, only when it is paired with Line
7. One way to fix this code so it compiles would be to add an if-then statement on
line 6. The other solution would be to remove line 7.

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

What is the output of the following code?
1: public class TernaryTester {
2: public static void main(String[] args) {
3: int x = 5;
4: System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7);
5: }}
A. 5
B. 4
C. 10
D. 8
E. 7
F. The code will not compile because of line 4.

A

D. As you learned in the section “Ternary Operator,” although parentheses are not
required, they do greatly increase code readability, such as the following equivalent
statement:
System.out.println((x > 2) ? ((x < 4) ? 10 : 8) : 7)
We apply the outside ternary operator fi rst, as it is possible the inner ternary expression
may never be evaluated. Since (x>2) is true, this reduces the problem to:
System.out.println((x < 4) ? 10 : 8)
Since x is greater than 2, the answer is 8, or option D in this case.

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

What is the output of the following code snippet?
3: boolean x = true, z = true;
4: int y = 20;
5: x = (y != 10) ^ (z=false);
6: System.out.println(x+”, “+y+”, “+z);
A. true, 10, true
B. true, 20, false
C. false, 20, true
D. false, 20, false
E. false, 20, true
F. The code will not compile because of line 5.

A

B. This example is tricky because of the second assignment operator embedded in line
5. The expression (z=false) assigns the value false to z and returns false for the
entire expression. Since y does not equal 10, the left-hand side returns true; therefore,
the exclusive or (^) of the entire expression assigned to x is true. The output reflects
these assignments, with no change to y, so option B is the only correct answer. The
code compiles and runs without issue, so option F is not correct.

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

How many times will the following code print “Hello World”?
3: for(int i=0; i<10 ; ) {
4: i = i++;
5: System.out.println(“Hello World”);
6: }
A. 9
B. 10
C. 11
D. The code will not compile because of line 3.
E. The code will not compile because of line 5.
F. The code contains an infinite loop and does not terminate.

A

F. In this example, the update statement of the for loop is missing, which is fine as the
statement is optional, so option D is incorrect. The expression inside the loop increments i but then assigns i the old value. Therefore, i ends the loop with the same value that it starts with: 0. The loop will repeat infinitely, outputting the same statement over
and over again because i remains 0 after every iteration of the loop

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

What is the output of the following code?
3: byte a = 40, b = 50;
4: byte sum = (byte) a + b;
5: System.out.println(sum);
A. 40
B. 50
C. 90
D. The code will not compile because of line 4.
E. An undefined value.

A

D. Line 4 generates a possible loss of precision compiler error. The cast operator has
the highest precedence, so it is evaluated first, casting a to a byte. Then, the addition is
evaluated, causing both a and b to be promoted to int values. The value 90 is an int
and cannot be assigned to the byte sum without an explicit cast, so the code does not
compile. The code could be corrected with parentheses around (a + b), in which case
option C would be the correct answer

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

What is the output of the following code?
1: public class ArithmeticSample {
2: public static void main(String[] args) {
3: int x = 5 * 4 % 3;
4: System.out.println(x);
5: }}
A. 2
B. 3
C. 5
D. 6
E. The code will not compile because of line 3.

A

A. The * and % have the same operator precedence, so the expression is evaluated
from left-to-right. The result of 5 * 4 is 20, and 20 % 3 is 2 (20 divided by 3 is 18, the
remainder is 2). The output is 2 and option A is the correct answer.

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

What is the output of the following code snippet?
3: int x = 0;
4: String s = null;
5: if(x == s) System.out.println(“Success”);
6: else System.out.println(“Failure”);
A. Success
B. Failure
C. The code will not compile because of line 4.
D. The code will not compile because of line 5

A

D. The variable x is an int and s is a reference to a String object. The two data types
are incomparable because neither variable can be converted to the other variable’s type.
The compiler error occurs on line 5 when the comparison is attempted, so the answer
is option D.

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

What is the output of the following code snippet?
3: int x1 = 50, x2 = 75;
4: boolean b = x1 >= x2;
5: if(b = true) System.out.println(“Success”);
6: else System.out.println(“Failure”);
A. Success
B. Failure
C. The code will not compile because of line 4.
D. The code will not compile because of line 5.

A

A. The code compiles successfully, so options C and D are incorrect. The value of b
after line 4 is false. However, the if-then statement on line 5 contains an assignment,
not a comparison. The variable b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success, so the answer is option A

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

What is the output of the following code snippet?
3: int c = 7;
4: int result = 4;
5: result += ++c;
6: System.out.println(result);
A. 8
B. 11
C. 12
D. 15
E. 16
F. The code will not compile because of line 5.

A

C. The code compiles successfully, so option F is incorrect. On line 5, the pre-increment operator is used, so c is incremented to 4 and the new value is returned to the
expression. The value of result is computed by adding 4 to the original value of 8,
resulting in a new value of 12, which is output on line 6. Therefore, option C is the
correct answer

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

What is the output of the following code snippet?
3: int x = 1, y = 15;
4: while x < 10
5: y––;
6: x++;
7: System.out.println(x+”, “+y);
A. 10, 5
B. 10, 6
C. 11, 5
D. The code will not compile because of line 3.
E. The code will not compile because of line 4.
F. The code contains an infinite loop and does not terminate.

A

E. This is actually a much simpler problem than it appears to be. The while statement
on line 4 is missing parentheses, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct
answer since the loop does not use curly braces to include x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the
output would be 10, 6 and option B would be correct.

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

What is the output of the following code snippet?
3: do {
4: int y = 1;
5: System.out.print(y++ + “ “);
6: } while(y <= 10);
A. 1 2 3 4 5 6 7 8 9
B. 1 2 3 4 5 6 7 8 9 10
C. 1 2 3 4 5 6 7 8 9 10 11
D. The code will not compile because of line 6.
E. The code contains an infinite loop and does not terminate.

A

D. The variable y is declared within the body of the do-while statement, so it is out of
scope on line 6. Line 6 generates a compiler error, so option D is the correct answer

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

What is the output of the following code snippet?
3: boolean keepGoing = true;
4: int result = 15, i = 10;
5: do {
6: i–;
7: if(i==8) keepGoing = false;
8: result -= 2;
9: } while(keepGoing);
10: System.out.println(result);
A. 7
B. 9
C. 10
D. 11
E. 15
F. The code will not compile because of line 8.

A

D. The code compiles without issue, so option F is incorrect. After the first execution of the loop, i is decremented to 9 and result to 13. Since i is not 8, keepGoing is
false, and the loop continues. On the next iteration, i is decremented to 8 and result
to 11. On the second execution, i does equal 8, so keepGoing is set to false. At the
conclusion of the loop, the loop terminates since keepGoing is no longer true. The
value of result is 11, and the correct answer is option D.

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

What is the output of the following code snippet?
3: int count = 0;
4: ROW_LOOP: for(int row = 1; row <=3; row++)
5: for(int col = 1; col <=2 ; col++) {
6: if(row * col % 2 == 0) continue ROW_LOOP;
7: count++;
8: }
9: System.out.println(count);
A. 1
B. 2
C. 3
D. 4
E. 6
F. The code will not compile because of line 6.

A

A. The expression on line 5 is true when row * col is an even number. On the first
iteration, row = 1 and col = 1, so the expression on line 6 is false, the continue is
skipped, and count is incremented to 1. On the second iteration, row = 1 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with
count still at 1. On the third iteration, row = 2 and col = 1, so the expression on line
6 is true and the continue ends the outer loop with count still at 1. On the fourth
iteration, row = 3 and col = 1, so the expression on line 6 is false, the continue is
skipped, and count is incremented to 2. Finally, on the fifth and final iteration, row
= 3 and col = 2, so the expression on line 6 is true and the continue ends the outer
loop with count still at 2. The result of 2 is displayed, so the answer is option B.

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

What is the result of the following code snippet?
3: int m = 9, n = 1, x = 0;
4: while(m > n) {
5: m–;
6: n += 2;
7: x += m + n;
8: }
9: System.out.println(x);
A. 11
B. 13
C. 23
D. 36
E. 50
F. The code will not compile because of line 7

A

D. Prior to the first iteration, m = 9, n = 1, and x = 0. After the iteration of the first
loop, m is updated to 8, n to 3, and x to the sum of the new values for m + n, 0 + 11 =
11. After the iteration of the second loop, m is updated to 7, n to 5, and x to the sum
of the new values for m + n, 11 + 12 = 23. After the iteration of the third loop, m is
updated to 6, n to 7, and x to the sum of the new values for m + n, 23 + 13 = 36. On
the fourth iteration of the loop, m > n evaluates to false, as 6 < 7 is not true. The
loop ends and the most recent value of x, 36, is output, so the correct answer is option
D.

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

What is the result of the following code snippet?
3: final char a = ‘A’, d = ‘D’;
4: char grade = ‘B’;
5: switch(grade) {
6: case a:
7: case ‘B’: System.out.print(“great”);
8: case ‘C’: System.out.print(“good”); break;
9: case d:
10: case ‘F’: System.out.print(“not good”);
11: }
A. great
B. greatgood
C. The code will not compile because of line 3.
D. The code will not compile because of line 6.
E. The code will not compile because of lines 6 and 9.

A

B. The code compiles and runs without issue, so options C, D, and E are not correct. The
value of grade is ‘B’ and there is a matching case statement that will cause “great” to
be printed. There is no break statement after the case, though, so the next case statement will be reached, and “good” will be printed. There is a break after this case statement, though, so the switch statement will end. The correct answer is thus option B.

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

Static member functions are not allowed to access non-static members. Why?

A

Static member functions don’t have access to a specific instance (this pointer) and are associated with the class itself. As a result, they cannot directly access non-static (instance) members to avoid ambiguity in the absence of a specific instance. Static functions operate at the class level, while non-static functions work with specific instances and have access to both static and non-static members. This separation helps maintain clarity in the design and prevents potential issues related to undefined behavior. If necessary, static functions can still interact with non-static members through explicit parameters or by creating instances within the function.

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

What is numeric promotion in Java? Provide examples.

A

Numeric promotion in Java is the automatic conversion of lower-ranked numeric data types to higher-ranked types to avoid data loss during mixed-type expressions. It ensures that operands of different types in an expression are compatible. For example, when combining an int and a double in an operation, the int is promoted to a double before the operation.

int and long in an addition operation:
int intValue = 5;
long longValue = 10L;
long result = intValue + longValue; // int is promoted to long

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

What is the String pool in Java and how is it used?

A

The String pool in Java is a pool of unique String objects stored in memory to optimize memory usage and improve performance. When a String is created using a literal (e.g., “example”), Java checks the pool. If a String with the same value already exists, the existing reference is returned instead of creating a new object. This reduces memory overhead by reusing existing String instances. String pool usage can be controlled using the intern() method, which adds the String to the pool if it’s not already present. Explicitly adding Strings to the pool can be beneficial in scenarios where many identical strings are created.

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

Explain the concept of Inheritance and how is it useful in OOP?

A

Inheritance in Object-Oriented Programming (OOP) is a mechanism that allows a class (subclass or derived class) to inherit properties and behaviors from another class (superclass or base class). The subclass can reuse and extend the functionality of the superclass, promoting code reuse and modularity. This relationship establishes an “is-a” connection between the subclass and superclass, facilitating a hierarchy of classes. Inheritance promotes the creation of more specialized classes by inheriting common features from a more general class, leading to a more organized and scalable code structure. It enhances code readability, maintenance, and reduces redundancy by encapsulating shared functionality in a common ancestor.

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

Polymorphism is one of the core concepts of OOP. What is Object Polymorphism and what are the three ways we can refer to an object?

A

Object Polymorphism in Object-Oriented Programming (OOP) allows objects of different types to be treated as objects of a common base type. It enables a single interface to represent various types of objects and supports dynamic method binding. The three ways to refer to an object are:

By its own class type: Referring to an object using its declared class type.
By its superclass type: Treating an object as an instance of its superclass, allowing for more general and abstract handling.
By an interface type: Referring to an object through an interface it implements, allowing for interaction based on shared behaviors defined by the interface.
These approaches facilitate flexibility, code extensibility, and the ability to write more generic and reusable code.

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

public class QuestionOne {
public static String concatStringMethod(StringBuilder sb1, StringBuilder sb2) {
String s1 = sb1.append(sb2).toString().trim().toLowerCase().concat(“HELLO”);
return s1;
}

public static void main(String[] args) {
    StringBuilder stringFoo = new StringBuilder("FoO");
    StringBuilder stringBar = new StringBuilder("bAr");

    QuestionOne.concatStringMethod(stringFoo, stringBar);
    System.out.println(stringFoo.append(stringBar));
} }
A

FoObArbAr

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

class Pyramid {
private double baseLength;
private double baseWidth;
private double height;
private double volume;

public Pyramid(double baseLength, double baseWidth, double height) {
    this.baseLength = baseLength;
    this.baseWidth = baseWidth;
    this.height = height;
    this();
}

public Pyramid() {
    volume = this.baseLength * this.baseWidth * this.height;
    this.volume /= 3;
}

public double getVolume() {
    return volume;
} }

public class QuestionTwo {
public static void main(String[] args) {
Pyramid p1 = new Pyramid(1, 2, 3);
Pyramid p2 = new Pyramid(2, 4, 6);
Pyramid p3 = new Pyramid();

    System.out.println(p1.getVolume());
    System.out.println(p2.getVolume());
    System.out.println(p3.getVolume());
} }
A

Constructor call must be the first statement in a constructor. There is an error in the Pyramid class constructor where the volume calculation is attempted in the no-argument constructor. In the no-argument constructor, this.baseLength, this.baseWidth, and this.height are used, but they may not have been initialized at this point, leading to potential issues in the volume calculation.

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

public class QuestionThree {
public static void main(String[] args) {
int x = 0;
int y = 0;
int z = 0;

    for (;; x++) {
        z = x % 5 == 0 ? x++ : y++;

        if (8 == x) {
            continue;
        }
        y += ++y;
        System.out.println("y: ", +y);

        if (y >= 20) {
            break;
        }
        System.out.println(x);
    }
} }
A

y: 1
1
y: 5
2
y: 13
3
y: 29

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

What is output by the following code? (Choose all that apply)
1: public class Fish {
2: public static void main(String[] args) {
3: int numFish = 4;
4: String fishType = “tuna”;
5: String anotherFish = numFish + 1;
6: System.out.println(anotherFish + “ “ + fishType);
7: System.out.println(numFish + “ “ + 1);
8: } }
A. 4 1
B. 41
C. 5
D. 5 tuna
E. 5tuna
F. 51tuna
G. The code does not compile.

A

G. Line 5 does not compile. This question is checking to see if you are paying attention
to the types. numFish is an int and 1 is an int. Therefore, we use numeric addition and
get 5. The problem is that we can’t store an int in a String variable. Supposing line 5
said String anotherFish = numFish + 1 + “”;. In that case, the answer would be
options A and D. The variable defined on line 5 would be the string “5”, and both output statements would use concatenation

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

Which of the following are output by this code? (Choose all that apply)
3: String s = “Hello”;
4: String t = new String(s);
5: if (“Hello”.equals(s)) System.out.println(“one”);
6: if (t == s) System.out.println(“two”);
7: if (t.equals(s)) System.out.println(“three”);
8: if (“Hello” == s) System.out.println(“four”);
9: if (“Hello” == t) System.out.println(“five”);
A. one
B. two
C. three
D. four
E. five
F. The code does not compile.

A

A, C, D. The code compiles fine. Line 3 points to the String in the string pool. Line 4
calls the String constructor explicitly and is therefore a different object than s. Lines 5
and 7 check for object equality, which is true, and so print one and three. Line 6 uses
object reference equality, which is not true since we have different objects. Line 7 also
compares references but is true since both references point to the object from the string
pool. Finally, line 8 compares one object from the string pool with one that was explicitly constructed and returns false.

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

Which are true statements? (Choose all that apply)
A. An immutable object can be modified.
B. An immutable object cannot be modified.
C. An immutable object can be garbage collected.
D. An immutable object cannot be garbage collected.
E. String is immutable.
F. StringBuffer is immutable.
G. StringBuilder is immutable

A

B, C, E. Immutable means the state of an object cannot change once it is created.
Immutable objects can be garbage collected just like mutable objects. String is immutable. StringBuilder can be mutated with methods like append(). Although StringBuffer isn’t on the exam, you should know about it anyway in case older questions haven’t been removed.

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

What is the result of the following code?
7: StringBuilder sb = new StringBuilder();
8: sb.append(“aaa”).insert(1, “bb”).insert(4, “ccc”);
9: System.out.println(sb);
A. abbaaccc
B. abbaccca
C. bbaaaccc
D. bbaaccca
E. An exception is thrown.
F. The code does not compile.

A

B. This example uses method chaining. After the call to append(), sb contains “aaa”.
That result is passed to the first insert() call, which inserts at index 1. At this point
sb contains abbbaa. That result is passed to the final insert(), which inserts at index
4, resulting in abbaccca.

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

What is the result of the following code?
2: String s1 = “java”;
3: StringBuilder s2 = new StringBuilder(“java”);
4: if (s1 == s2)
5: System.out.print(“1”);
6: if (s1.equals(s2))
7: System.out.print(“2”);
A. 1
B. 2
C. 12
D. No output is printed.
E. An exception is thrown.
F. The code does not compile

A

F. The question is trying to distract you into paying attention to logical equality versus
object reference equality. It is hoping you will miss the fact that line 4 does not compile. Java does not allow you to compare String and StringBuilder using ==.

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

What is the result of the following code?
public class Lion {
public void roar(String roar1, StringBuilder roar2) {
roar1.concat(“!!!”);
roar2.append(“!!!”);
}
public static void main(String[] args) {
String roar1 = “roar”;
StringBuilder roar2 = new StringBuilder(“roar”);
new Lion().roar(roar1, roar2);
System.out.println(roar1 + “ “ + roar2);
} }
A. roar roar
B. roar roar!!!
C. roar!!! roar
D. roar!!! roar!!!
E. An exception is thrown.
F. The code does not compile

A

B. A String is immutable. Calling concat() returns a new String but does not change
the original. A StringBuilder is mutable. Calling append() adds characters to the
existing character sequence along with returning a reference to the same object.

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

Which are the results of the following code? (Choose all that apply)
String letters = “abcdef”;
System.out.println(letters.length());
System.out.println(letters.charAt(3));
System.out.println(letters.charAt(6));
A. 5
B. 6
C. c
D. d
E. An exception is thrown.
F. The code does not compile.

A

B, D, E. length() is simply a count of the number of characters in a String. In this
case, there are six characters. charAt() returns the character at that index. Remember
that indexes are zero based, which means that index 3 corresponds to d and index 6
corresponds to 1 past the end of the array. A StringIndexOutOfBoundsException is
thrown for the last line.

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

Which are the results of the following code? (Choose all that apply)
String numbers = “012345678”;
System.out.println(numbers.substring(1, 3));
System.out.println(numbers.substring(7, 7));
System.out.println(numbers.substring(7));
A. 12
B. 123
C. 7
D. 78
E. A blank line.
F. An exception is thrown.
G. The code does not compile.

A

A, D, E. substring() has two forms. The first takes the index to start with and the
index to stop immediately before. The second takes just the index to start with and
goes to the end of the String. Remember that indexes are zero based. The first call
starts at index 1 and ends with index 2 since it needs to stop before index 3. The second call starts at index 7 and ends in the same place, resulting in an empty String.
This prints out a blank line. The final call starts at index 7 and goes to the end of the
String.

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

What is the result of the following code? (Choose all that apply)
13: String a = “”;
14: a += 2;
15: a += ‘c’;
16: a += false;
17: if ( a == “2cfalse”) System.out.println(“==”);
18: if ( a.equals(“2cfalse”)) System.out.println(“equals”);
A. Compile error on line 14.
B. Compile error on line 15.
C. Compile error on line 16.
D. Compile error on another line.
E. ==
F. equals
G. An exception is thrown.

A

F. a += 2 expands to a = a + 2. A String concatenated with any other type gives
a String. Lines 14, 15, and 16 all append to a, giving a result of “2cfalse”. The if
statement on line 18 returns false because the values of the two String objects are the
same using object equality. The if statement on line 17 returns false because the two
String objects are not the same in memory. One comes directly from the string pool
and the other comes from building using String operations.

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

What is the result of the following code?
3: String s = “purr”;
4: s.toUpperCase();
5: s.trim();
6: s.substring(1, 3);
7: s += “ two”;
8: System.out.println(s.length());
A. 2
B. 4
C. 8
D. 10
E. An exception is thrown.
F. The code does not compile.

A

C. This question is trying to see if you know that String objects are immutable. Line
4 returns “PURR” but the result is ignored and not stored in s. Line 5 returns “purr”
since there is no whitespace present but the result is again ignored. Line 6 returns “ur”
because it starts with index 1 and ends before index 3 using zero-based indexes. The
result is ignored again. Finally, on line 6 something happens. We concatenate four new
characters to s and now have a String of length 8.

61
Q

What is the result of the following code?
4: int total = 0;
5: StringBuilder letters = new StringBuilder(“abcdefg”);
6: total += letters.substring(1, 2).length();
7: total += letters.substring(6, 6).length();
8: total += letters.substring(6, 5).length();
9: System.out.println(total);
A. 1
B. 2
C. 3
D. 7
E. An exception is thrown.
F. The code does not compile

A

E. Line 6 adds 1 to total because substring() includes the starting index but not
the ending index. Line 7 adds 0 to total. Line 8 is a problem: Java does not allow the
indexes to be specified in reverse order and the code throws a StringIndexOutOfBoundsException.

62
Q

What is the result of the following code? (Choose all that apply)
StringBuilder numbers = new StringBuilder(“0123456789”);
numbers.delete(2, 8);
numbers.append(“-“).insert(2, “+”);
System.out.println(numbers);
A. 01+89–
B. 012+9–
C. 012+–9
D. 0123456789
E. An exception is thrown.
F. The code does not compile.

A

A. First, we delete the characters at index 2 until the character one before index 8. At
this point, 0189 is in numbers. The following line uses method chaining. It appends a
dash to the end of the characters sequence, resulting in 0189–, and then inserts a plus
sign at index 2, resulting in 01+89–.

63
Q

What is the result of the following code?
StringBuilder b = “rumble”;
b.append(4).deleteCharAt(3).delete(3, b.length() - 1);
System.out.println(b);
A. rum
B. rum4
C. rumb4
D. rumble4
E. An exception is thrown.
F. The code does not compile.

A

F. This is a trick question. The first line does not compile because you cannot
assign a String to a StringBuilder. If that line were StringBuilder b = new
StringBuilder(“rumble”), the code would compile and print rum4. Watch out for this
sort of trick on the exam. You could easily spend a minute working out the character
positions for no reason at all.

64
Q

Which of the following can replace line 4 to print “avaJ”? (Choose all that apply)
3: StringBuilder puzzle = new StringBuilder(“Java”);
4: // INSERT CODE HERE
5: System.out.println(puzzle);
A. puzzle.reverse();
B. puzzle.append(“vaJ$”).substring(0, 4);
C. puzzle.append(“vaJ$”).delete(0, 3).deleteCharAt(puzzle.length() - 1);
D. puzzle.append(“vaJ$”).delete(0, 3).deleteCharAt(puzzle.length());
E. None of the above

A

A, C. The reverse() method is the easiest way of reversing the characters in a StringBuilder; therefore, option A is correct. Option B is a nice distraction—it does in fact
return “avaJ”. However, substring() returns a String, which is not stored anywhere.
Option C uses method chaining. First it creates the value “JavavaJ$”. Then it removes
the first three characters, resulting in “avaJ$”. Finally, it removes the last character,
resulting in “avaJ”. Option D throws an exception because you cannot delete the character after the last index. Remember that deleteCharAt() uses indexes that are zero
based and length() counts starting with 1.

65
Q

Which of these compile when replacing line 8? (Choose all that apply)
7: char[]c = new char[2];
8: // INSERT CODE HERE
A. int length = c.capacity;
B. int length = c.capacity();
C. int length = c.length;
D. int length = c.length();
E. int length = c.size;
F. int length = c.size();
G. None of the above

A

C. Arrays define a property called length. It is not a method, so parentheses are not
allowed

66
Q

Which of these compile when replacing line 8? (Choose all that apply)
7: ArrayList l = new ArrayList();
8: // INSERT CODE HERE
A. int length = l.capacity;
B. int length = l.capacity();
C. int length = l.length;
D. int length = l.length();
E. int length = l.size;
F. int length = l.size();
G. None of the above.

A

F. The ArrayList class defines a method called size().

67
Q

Which of the following are true? (Choose all that apply)
A. An array has a fixed size.
B. An ArrayList has a fixed size.
C. An array allows multiple dimensions.
D. An array is ordered.
E. An ArrayList is ordered.
F. An array is immutable.
G. An ArrayList is immutable.

A

A, C, D, E. An array is not able to change size and can have multiple dimensions. Both
an array and ArrayList are ordered and have indexes. Neither is immutable. The elements can change in value.

68
Q

Which of the following are true? (Choose all that apply)
A. Two arrays with the same content are equal.
B. Two ArrayLists with the same content are equal.
C. If you call remove(0) using an empty ArrayList object, it will compile successfully.
D. If you call remove(0) using an empty ArrayList object, it will run successfully.
E. None of the above.

A

B, C. An array does not override equals() and so uses object equality. ArrayList does
override equals() and defines it as the same elements in the same order. The compiler
does not know when an index is out of bounds and thus can’t give you a compiler
error. The code will throw an exception at runtime, though.

69
Q

What is the result of the following statements?
6: List<String> list = new ArrayList<String>();
7: list.add("one");
8: list.add("two");
9: list.add(7);
10: for(String s : list) System.out.print(s);
A. onetwo
B. onetwo7
C. onetwo followed by an exception
D. Compiler error on line 9.
E. Compiler error on line 10.</String></String>

A

D. The code does not compile because list is instantiated using generics. Only String
objects can be added to list and 7 is an int.

70
Q

What is the result of the following statements?
3: ArrayList<Integer> values = new ArrayList<>();
4: values.add(4);
5: values.add(5);
6: values.set(1, 6);
7: values.remove(0);
8: for (Integer v : values) System.out.print(v);
A. 4
B. 5
C. 6
D. 46
E. 45
F. An exception is thrown.
G. The code does not compile</Integer>

A

C. After line 4, values has one element (4). After line 5, values has two elements (4,
5). After line 6, values has two elements (4, 6) because set() does a replace. After line
7, values has only one element (6).

71
Q

What is the result of the following?
int[] random = { 6, -4, 12, 0, -10 };
int x = 12;
int y = Arrays.binarySearch(random, x);
System.out.println(y);
A. 2
B. 4
C. 6
D. The result is undefined.
E. An exception is thrown.
F. The code does not compile.

A

D. The code compiles and runs fine. However, an array must be sorted for binarySearch() to return a meaningful result.

72
Q

What is the result of the following?
4: List<Integer> list = Arrays.asList(10, 4, -1, 5);
5: Collections.sort(list);
6: Integer array[] = list.toArray(new Integer[4]);
7: System.out.println(array[0]);
A. –1
B. 10
C. Compiler error on line 4.
D. Compiler error on line 5.
E. Compiler error on line 6.
F. An exception is thrown.</Integer>

A

A. Line 4 creates a fixed size array of size 4. Line 5 sorts it. Line 6 converts it back to
an array. The brackets aren’t in the traditional place, but they are still legal. Line 7
prints the first element, which is now –1.

73
Q

What is the result of the following?
6: String [] names = {“Tom”, “Dick”, “Harry”};
7: List<String> list = names.asList();
8: list.set(0, "Sue");
9: System.out.println(names[0]);
A. Sue
B. Tom
C. Compiler error on line 7.
D. Compiler error on line 8.
E. An exception is thrown</String>

A

C. Converting from an array to an ArrayList uses Arrays.asList(names). There is
no asList() method on an array instance. If this code were corrected to compile, the
answer would be option A

74
Q

What is the result of the following?
List<String> hex = Arrays.asList("30", "8", "3A", "FF");
Collections.sort(hex);
int x = Collections.binarySearch(hex, "8");
int y = Collections.binarySearch(hex, "3A");
int z = Collections.binarySearch(hex, "4F");
System.out.println(x + " " + y + " " + z);
A 0 1 –2
B. 0 1 –3
C. 2 1 –2
D. 2 1 –3
E. None of the above.
F. The code doesn’t compile</String>

A

D. After sorting, hex contains [30, 3A, 8, FF]. Remember that numbers sort before
letters and strings sort alphabetically. This makes 30 come before 8. A binary search
correctly finds 8 at index 2 and 3A at index 1. It cannot find 4F but notices it should
be at index 2. The rule when an item isn’t found is to negate that index and subtract 1.
Therefore, we get –2–1, which is –3.

75
Q

Which of the following are true statements about the following code? (Choose all that
apply)
4: List<Integer> ages = new ArrayList<>();
5: ages.add(Integer.parseInt("5"));
6: ages.add(Integer.valueOf("6"));
7: ages.add(7);
8: ages.add(null);
9: for (int age : ages) System.out.print(age);
A. The code compiles.
B. The code throws a runtime exception.
C. Exactly one of the add statements uses autoboxing.
D. Exactly two of the add statements use autoboxing.
E. Exactly three of the add statements use autoboxing</Integer>

A

A, B, D. Lines 5 and 7 use autoboxing to convert an int to an Integer. Line 6 does
not because valueOf() returns an Integer. Line 8 does not because null is not an int.
The code does not compile. However, when the for loop tries to unbox null into an
int, it fails and throws a NullPointerException.

76
Q

What is the result of the following?
List<String> one = new ArrayList<String>();
one.add("abc");
List<String> two = new ArrayList<>();
two.add("abc");
if (one == two)
System.out.println("A");
else if (one.equals(two))
System.out.println("B");
else
System.out.println("C");
A. A
B. B
C. C
D. An exception is thrown.
E. The code does not compile</String></String></String>

A

B. The first if statement is false because the variables do not point to the same object.
The second if statement is true because ArrayList implements equality to mean the
same elements in the same order.

77
Q

Which of the following can be inserted into the blank to create a date of June 21, 2014?
(Choose all that apply)
import java.time.*;
public class StartOfSummer {
public static void main(String[] args) {
LocalDate date = ____________________________
}
}
A. new LocalDate(2014, 5, 21);
B. new LocalDate(2014, 6, 21);
C. LocalDate.of(2014, 5, 21);
D. LocalDate.of(2014, 6, 21);
E. LocalDate.of(2014, Calendar.JUNE, 21);
F. LocalDate.of(2014, Month.JUNE, 21);

A

D, F. Options A and B are incorrect because LocalDate does not have a public constructor. Option C is incorrect because months start counting with 1 rather than 0.
Option E is incorrect because it uses the old pre–Java 8 way of counting months, again
beginning with 0. Options D and F are both correct ways of specifying the desired
date.

78
Q

What is the output of the following code?
LocalDate date = LocalDate.parse(“2018-04-30”, DateTimeFormatter.ISO_LOCAL_
DATE);
date.plusDays(2);
date.plusHours(3);
System.out.println(date.getYear() + “ “ + date.getMonth() + “ “
+ date.getDayOfMonth());
A. 2018 APRIL 2
B. 2018 APRIL 30
C. 2018 MAY 2
D. The code does not compile.
E. A runtime exception is thrown.

A

D. A LocalDate does not have a time element. Therefore, it has no method to add
hours and the code does not compile.

79
Q

What is the output of the following code?
LocalDate date = LocalDate.of(2018, Month.APRIL, 40);
System.out.println(date.getYear() + “ “ + date.getMonth() + “ “
+ date.getDayOfMonth());
A. 2018 APRIL 4
B. 2018 APRIL 30
C. 2018 MAY 10
D. Another date.
E. The code does not compile.
F. A runtime exception is thrown

A

F. Java throws an exception if invalid date values are passed. There is no 40th day in April—or any other month for that matter.

80
Q

What is the output of the following code?
LocalDate date = LocalDate.of(2018, Month.APRIL, 30);
date.plusDays(2);
date.plusYears(3);
System.out.println(date.getYear() + “ “ + date.getMonth() + “ “
+ date.getDayOfMonth());
A. 2018 APRIL 2
B. 2018 APRIL 30
C. 2018 MAY 2
D. 2021 APRIL 2
E. 2021 APRIL 30
F. 2021 MAY 2
G. A runtime exception is thrown

A

B. The date starts out as April 30, 2018. Since dates are immutable and the plus methods have their return values ignored, the result is unchanged. Therefore, option B is
correct.

81
Q

What is the output of the following code?
LocalDateTime d = LocalDateTime.of(2015, 5, 10, 11, 22, 33);
Period p = Period.of(1, 2, 3);
d = d.minus(p);
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
System.out.println(d.format(f));
A. 3/7/14 11:22 AM
B. 5/10/15 11:22 AM
C. 3/7/14
D. 5/10/15
E. 11:22 AM
F. The code does not compile.
G. A runtime exception is thrown.

A

E. Even though d has both date and time, the formatter only outputs time.

82
Q

What is the output of the following code?
LocalDateTime d = LocalDateTime.of(2015, 5, 10, 11, 22, 33);
Period p = Period.ofDays(1).ofYears(2);
d = d.minus(p);
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime(FormatStyle
.SHORT);
System.out.println(f.format(d));
A. 5/9/13 11:22 AM
B. 5/10/13 11:22 AM
C. 5/9/14
D. 5/10/14
E. The code does not compile.
F. A runtime exception is thrown.

A

B. Period does not allow chaining. Only the last Period method called counts, so only the two years are subtracted.

83
Q

Which of the following can fill in the blank in this code to make it compile? (Choose all
that apply)
public class Ant {
_____ void method() { }
}
A. default
B. final
C. private
D. Public
E. String
F. zzz:

A

B, C. void is a return type. Only the access modifier or optional specifiers are allowed
before the return type. Option C is correct, creating a method with private access.
Option B is correct, creating a method with default access and the optional specifier
final. Since default access does not require a modifier, we get to jump right to final. Option A is incorrect because default access omits the access modifier rather than specifying default. Option D is incorrect because Java is case sensitive. It would have been
correct if public were the choice. Option E is incorrect because the method already has
a void return type. Option F is incorrect because labels are not allowed for methods.

84
Q

Which of the following compile? (Choose all that apply)
A. final static void method4() { }
B. public final int void method() { }
C. private void int method() { }
D. static final void method3() { }
E. void final method() {}
F. void public method() { }

A

A, D. Options A and D are correct because the optional specifiers are allowed in any
order. Options B and C are incorrect because they each have two return types. Options
E and F are incorrect because the return type is before the optional specifier and access
modifier, respectively.

85
Q

Which of the following methods compile? (Choose all that apply)
A. public void methodA() { return;}
B. public void methodB() { return null;}
C. public void methodD() {}
D. public int methodD() { return 9;}
E. public int methodE() { return 9.0;}
F. public int methodF() { return;}
G. public int methodG() { return null;}

A

A, C, D. Options A and C are correct because a void method is allowed to have a
return statement as long as it doesn’t try to return a value. Options B and G do not
compile because null requires a reference object as the return type. void is not a reference object since it is a marker for no return type. int is not a reference object since it
is a primitive. Option D is correct because it returns an int value. Option E does not
compile because it tries to return a double when the return type is int. Since a double
cannot be assigned to an int, it cannot be returned as one either. Option F does not
compile because no value is actually returned.

86
Q

Which of the following compile? (Choose all that apply)
A. public void moreA(int… nums) {}
B. public void moreB(String values, int… nums) {}
C. public void moreC(int… nums, String values) {}
D. public void moreD(String… values, int… nums) {}
E. public void moreE(String[] values, …int nums) {}
F. public void moreF(String… values, int[] nums) {}
G. public void moreG(String[] values, int[] nums) {}

A

A, B, G. Options A and B are correct because the single vararg parameter is the last
parameter declared. Option G is correct because it doesn’t use any vararg parameters
at all. Options C and F are incorrect because the vararg parameter is not last. Option
D is incorrect because two vararg parameters are not allowed in the same method.
Option E is incorrect because the … for a vararg must be after the type, not before it.

87
Q

Given the following method, which of the method calls return 2? (Choose all that apply)
public int howMany(boolean b, boolean… b2) {
return b2.length;
}
A. howMany();
B. howMany(true);
C. howMany(true, true);
D. howMany(true, true, true);
E. howMany(true, {true});
F. howMany(true, {true, true});
G. howMany(true, new boolean[2]);

A

D, G. Option D passes the initial parameter plus two more to turn into a vararg array
of size 2. Option G passes the initial parameter plus an array of size 2. Option A does
not compile because it does not pass the initial parameter. Options E and F do not
compile because they do not declare an array properly. It should be new boolean[]
{true}. Option B creates a vararg array of size 0 and option C creates a vararg array of
size 1.

88
Q

Which of the following are true? (Choose all that apply)
A. Package private access is more lenient than protected access.
B. A public class that has private fields and package private methods is not visible to
classes outside the package.
C. You can use access modifiers so only some of the classes in a package see a particular
package private class.
D. You can use access modifiers to allow read access to all methods, but not any instance
variables.
E. You can use access modifiers to restrict read access to all classes that begin with the
word Test.

A

D. Option D is correct. This is the common implementation for encapsulation by setting all fields to be private and all methods to be public. Option A is incorrect because
protected access allows everything that package private access allows and additionally
allows subclasses access. Option B is incorrect because the class is public. This means
that other classes can see the class. However, they cannot call any of the methods or
read any of the fields. It is essentially a useless class. Option C is incorrect because
package private access applies to the whole package. Option E is incorrect because Java
has no such capability.

89
Q

Given the following my.school.ClassRoom and my.city.School class definitions, which
line numbers in main() generate a compiler error? (Choose all that apply)
1: package my.school;
2: public class Classroom {
3: private int roomNumber;
4: protected String teacherName;
5: static int globalKey = 54321;
6: public int floor = 3;
7: Classroom(int r, String t) {
8: roomNumber = r;
9: teacherName = t; } }
1: package my.city;
2: import my.school.*;
3: public class School {
4: public static void main(String[] args) {
5: System.out.println(Classroom.globalKey);
6: Classroom room = new Classroom(101, ““Mrs. Anderson”);
7: System.out.println(room.roomNumber);
8: System.out.println(room.floor);
9: System.out.println(room.teacherName); } }
A. None, the code compiles fine.
B. Line 5
C. Line 6
D. Line 7
E. Line 8
F. Line 9

A

B, C, D, F. The two classes are in different packages, which means private access and
default (package private) access will not compile. Additionally, protected access will
not compile since School does not inherit from Classroom. Therefore, only line 8 will
compile because it uses public access.

90
Q

Which of the following are true? (Choose all that apply)
A. Encapsulation uses package private instance variables.
B. Encapsulation uses private instance variables.
C. Encapsulation allows setters.
D. Immutability uses package private instance variables.
E. Immutability uses private instance variables.
F. Immutability allows setters.

A

B, C, E. Encapsulation requires using methods to get and set instance variables so
other classes are not directly using them. Instance variables must be private for this
to work. Immutability takes this a step further, allowing only getters, so the instance
variables do not change state.

91
Q

Which are methods using JavaBeans naming conventions for accessors and mutators?
(Choose all that apply)
A. public boolean getCanSwim() { return canSwim;}
B. public boolean canSwim() { return numberWings;}
C. public int getNumWings() { return numberWings;}
D. public int numWings() { return numberWings;}
E. public void setCanSwim(boolean b) { canSwim = b;}

A

C, E. Option A is incorrect because the property is of type boolean and getters must
begin with is for booleans. Options B and D are incorrect because they don’t follow
the naming convention of beginning with get/is/set. Options C and E follow normal
getter and setter conventions.

92
Q

What is the output of the following code?
1: package rope;
2: public class Rope {
3: public static int LENGTH = 5;
4: static {
5: LENGTH = 10;
6: }
7: public static void swing() {
8: System.out.print(“swing “);
9: }
10: }
1: import rope.;
2: import static rope.Rope.
;
3: public class Chimp {
4: public static void main(String[] args) {
5: Rope.swing();
6: new Rope().swing();
7: System.out.println(LENGTH);
8: }
9: }
A. swing swing 5
B. swing swing 10
C. Compiler error on line 2 of Chimp.
D. Compiler error on line 5 of Chimp.
E. Compiler error on line 6 of Chimp.
F. Compiler error on line 7 of Chimp.

A

B. Rope runs line 3, setting LENGTH to 5, then immediately after runs the static initializer, which sets it to 10. Line 5 calls the static method normally and prints swing.
Line 6 also calls the static method. Java allows calling a static method through an
instance variable. Line 7 uses the static import on line 2 to reference LENGTH

93
Q

Which are true of the following code? (Choose all that apply)
1: public class Rope {
2: public static void swing() {
3: System.out.print(“swing “);
4: }
5: public void climb() {
6: System.out.println(“climb “);
7: }
8: public static void play() {
9: swing();
10: climb();
11: }
12: public static void main(String[] args) {
13: Rope rope = new Rope();
14: rope.play();
15: Rope rope2 = null;
16: rope2.play();
17: }
18: }
A. The code compiles as is.
B. There is exactly one compiler error in the code.
C. There are exactly two compiler errors in the code.
D. If the lines with compiler errors are removed, the output is climb climb.
E. If the lines with compiler errors are removed, the output is swing swing.
F. If the lines with compile errors are removed, the code throws a NullPointerException

A

B, E. Line 10 does not compile because static methods are not allowed to call instance
methods. Even though we are calling play() as if it were an instance method and an
instance exists, Java knows play() is really a static method and treats it as such. If line
10 is removed, the code works. It does not throw a NullPointerException on line 16
because play() is a static method. Java looks at the type of the reference for rope2 and
translates the call to Rope.play().

94
Q

What is the output of the following code?
import rope.;
import static rope.Rope.
;
public class RopeSwing {
private static Rope rope1 = new Rope();
private static Rope rope2 = new Rope();
{
System.out.println(rope1.length);
}
public static void main(String[] args) {
rope1.length = 2;
rope2.length = 8;
System.out.println(rope1.length);
}
}
package rope;
public class Rope {
public static int length = 0;
}
A. 02
B. 08
C. 2
D. 8
E. The code does not compile.
F. An exception is thrown

A

D. There are two details to notice in this code. First, note that RopeSwing has an
instance initializer and not a static initializer. Since RopeSwing is never constructed,
the instance initializer does not run. The other detail is that length is static. Changes
from one object update this common static variable.

95
Q

How many compiler errors are in the following code?
1: public class RopeSwing {
2: private static final String leftRope;
3: private static final String rightRope;
4: private static final String bench;
5: private static final String name = “name”;
6: static {
7: leftRope = “left”;
8: rightRope = “right”;
9: }
10: static {
11: name = “name”;
12: rightRope = “right”;
13: }
14: public static void main(String[] args) {
15: bench = “bench”;
16: }
17: }
A. 0
B. 1
C. 2
D. 3
E. 4
F. 5

A

E. static final variables must be set exactly once, and it must be in the declaration
line or in a static initialization block. Line 4 doesn’t compile because bench is not set
in either of these locations. Line 15 doesn’t compile because final variables are not
allowed to be set after that point. Line 11 doesn’t compile because name is set twice:
once in the declaration and again in the static block. Line 12 doesn’t compile because
rightRope is set twice as well. Both are in static initialization blocks.

96
Q

Which of the following can replace line 2 to make this code compile? (Choose
all that apply)
1: import java.util.*;
2: // INSERT CODE HERE
3: public class Imports {
4: public void method(ArrayList<String> list) {
5: sort(list);
6: }
7: }
A. import static java.util.Collections;
B. import static java.util.Collections.*;
C. import static java.util.Collections.sort(ArrayList<String>);
D. static import java.util.Collections;
E. static import java.util.Collections.*;
F. static import java.util.Collections.sort(ArrayList<String>);</String></String></String>

A

B. The two valid ways to do this are import static java.util.Collections.*; and
import static java.util.Collections.sort;. Option A is incorrect because you
can only do a static import on static members. Classes such as Collections require
a regular import. Option C is nonsense as method parameters have no business in
an import. Options D, E, and F try to trick you into reversing the syntax of import
static.

97
Q

What is the result of the following statements?
1: public class Test {
2: public void print(byte x) {
3: System.out.print(“byte”);
4: }
5: public void print(int x) {
6: System.out.print(“int”);
7: }
8: public void print(float x) {
9: System.out.print(“float”);
10: }
11: public void print(Object x) {
12: System.out.print(“Object”);
13: }
14: public static void main(String[] args) {
15: Test t = new Test();
16: short s = 123;
17: t.print(s);
18: t.print(true);
19: t.print(6.789);
20: }
21: }
A. bytefloatObject
B. intfloatObject
C. byteObjectfloat
D. intObjectfloat
E. intObjectObject
F. byteObjectObject

A

E. The argument on line 17 is a short. It can be promoted to an int, so print() on
line 5 is invoked. The argument on line 18 is a boolean. It can be autoboxed to a boolean, so print() on line 11 is invoked. The argument on line 19 is a double. It can
be autoboxed to a double, so print() on line 11 is invoked. Therefore, the output is
intObjectObject and the correct answer is option E

98
Q

What is the result of the following program?
1: public class Squares {
2: public static long square(int x) {
3: long y = x * (long) x;
4: x = -1;
5: return y;
6: }
7: public static void main(String[] args) {
8: int value = 9;
9: long result = square(value);
10: System.out.println(value);
11: } }
A. -1
B. 9
C. 81
D. Compiler error on line 9.
E. Compiler error on a different line.

A

B. Since Java is pass-by-value and the variable on line 8 never gets reassigned, it stays
as 9. In the method square, x starts as 9. y becomes 81 and then x gets set to –1. Line 9
does set result to 81. However, we are printing out value and that is still 9.

99
Q

Which of the following are output by the following code? (Choose all that apply)
public class StringBuilders {
public static StringBuilder work(StringBuilder a,
StringBuilder b) {
a = new StringBuilder(“a”);
b.append(“b”);
return a;
}
public static void main(String[] args) {
StringBuilder s1 = new StringBuilder(“s1”);
StringBuilder s2 = new StringBuilder(“s2”);
StringBuilder s3 = work(s1, s2);
System.out.println(“s1 = “ + s1);
System.out.println(“s2 = “ + s2);
System.out.println(“s3 = “ + s3);
}
}
A. s1 = a
B. s1 = s1
C. s2 = s2
D. s2 = s2b
E. s3 = a
F. s3 = null
G. The code does not compile

A

B, D, E. Since Java is pass-by-reference, assigning a new object to a does not change the
caller. Calling append() does affect the caller because both the method parameter and caller have a reference to the same object. Finally, returning a value does pass the reference to the caller for assignment to s3.

100
Q

Which of the following are true? (Choose 2)
A. this() can be called from anywhere in a constructor.
B. this() can be called from any instance method in the class.
C. this.variableName can be called from any instance method in the class.
D. this.variableName can be called from any static method in the class.
E. You must include a default constructor in the code if the compiler does not include one.
F. You can call the default constructor written by the compiler using this().
G. You can access a private constructor with the main() method.

A

C, G. Since the main() method is in the same class, it can call private methods in the
class. this() may only be called as the first line of a constructor. this.variableName
can be called from any instance method to refer to an instance variable. It cannot be
called from a static method because there is no instance of the class to refer to. Option
F is tricky. The default constructor is only written by the compiler if no user-defined
constructors were provided. this() can only be called from a constructor in the same
class. Since there can be no user-defined constructors in the class if a default constructor was created, it is impossible for option F to be true.

101
Q

Which of these classes compile and use a default constructor? (Choose all that apply)
A. public class Bird { }
B. public class Bird { public bird() {} }
C. public class Bird { public bird(String name) {} }
D. public class Bird { public Bird() {} }
E. public class Bird { Bird(String name) {} }
F. public class Bird { private Bird(int age) {} }
G. public class Bird { void Bird() { }

A

A, G. Options B and C don’t compile because the constructor name must match the
classname. Since Java is case sensitive, these don’t match. Options D, E, and F all compile and provide one user-defined constructor. Since a constructor is coded, a default
constructor isn’t supplied. Option G defines a method, but not a constructor. Option A
does not define a constructor, either. Since no constructor is coded, a default constructor is provided for options A and G.

102
Q

Which code can be inserted to have the code print 2?
public class BirdSeed {
private int numberBags;
boolean call;
public BirdSeed() {
// LINE 1
call = false;
// LINE 2
}
public BirdSeed(int numberBags) {
this.numberBags = numberBags;
}
public static void main(String[] args) {
BirdSeed seed = new BirdSeed();
System.out.println(seed.numberBags);
} }
A. Replace line 1 with BirdSeed(2);
B. Replace line 2 with BirdSeed(2);
C. Replace line 1 with new BirdSeed(2);
D. Replace line 2 with new BirdSeed(2);
E. Replace line 1 with this(2);
F. Replace line 2 with this(2);

A

E. Options A and B will not compile because constructors cannot be called without
new. Options C and D will compile but will create a new object rather than setting the fields in this one. Option F will not compile because this() must be the first line of a constructor. Option E is correct.

103
Q

Which of the following complete the constructor so that this code prints out 50? (Choose
all that apply)
public class Cheetah {
int numSpots;
public Cheetah(int numSpots) {
// INSERT CODE HERE
}
public static void main(String[] args) {
System.out.println(new Cheetah(50).numSpots);
}
}
A. numSpots = numSpots;
B. numSpots = this.numSpots;
C. this.numSpots = numSpots;
D. numSpots = super.numSpots;
E. super.numSpots = numSpots;
F. None of the above.

A

C. Within the constructor numSpots refers to the constructor parameter. The instance
variable is hidden because they have the same name. this.numSpots tells Java to use
the instance variable. In the main() method, numSpots refers to the instance variable.
Option A sets the constructor parameter to itself, leaving the instance variable as 0.
Option B sets the constructor parameter to the value of the instance variable, making
them both 0. Option C is correct, setting the instance variable to the value of the constructor parameter. Options D and E do not compile.

104
Q

What is the result of the following?
1: public class Order {
2: static String result = “”;
3: { result += “c”; }
4: static
5: { result += “u”; }
6: { result += “r”; }
7: }
1: public class OrderDriver {
2: public static void main(String[] args) {
3: System.out.print(Order.result + “ “);
4: System.out.print(Order.result + “ “);
5: new Order();
6: new Order();
7: System.out.print(Order.result + “ “);
8: }
9: }
A. curur
B. ucrcr
C. u ucrcr
D. u u curcur
E. u u ucrcr
F. ur ur urc
G. The code does not compile.

A

E. On line 3 of OrderDriver, we refer to Order for the first time. At this point the statics in Order get initialized. In this case, the statics are the static declaration of result
and the static initializer. result is u at this point. On line 4, result is the same
because the static initialization is only run once. On line 5, we create a new Order, which triggers the instance initializers in the order they appear in the file. Now result is ucr. Line 6 creates another Order, triggering another set of initializers. Now result
is ucrcr. Notice how the static is on a different line than the initialization code in
lines 4–5 of Order. The exam may try to trick you by formatting the code like this to confuse you.

105
Q

What is the result of the following?
1: public class Order {
2: String value = “t”;
3: { value += “a”; }
4: { value += “c”; }
5: public Order() {
6: value += “b”;
7: }
8: public Order(String s) {
9: value += s;
10: }
11: public static void main(String[] args) {
12: Order order = new Order(“f”);
13: order = new Order();
14: System.out.println(order.value);
15: } }
A. tacb
B. tacf
C. tacbf
D. tacfb
E. tacftacb
F. The code does not compile.
G. An exception is thrown.

A

A. Line 4 instantiates an Order. Java runs the declarations and instance initializers first
in the order they appear. This sets value to tacf. Line 5 creates another Order and
initializes value to tacb. The object on line 5 is stored in the same variable line 4 used. This makes the object created on line 4 unreachable. When value is printed, it is the instance variable in the object created on line 5.

106
Q

Which of the following will compile when inserted in the following code? (Choose
all that apply)
public class Order3 {
final String value1 = “1”;
static String value2 = “2”;
String value3 = “3”;
{
// CODE SNIPPET 1
}
static {
// CODE SNIPPET 2
}
}
A. value1 = “d”; instead of // CODE SNIPPET 1
B. value2 = “e”; instead of // CODE SNIPPET 1
C. value3 = “f”; instead of // CODE SNIPPET 1
D. value1 = “g”; instead of // CODE SNIPPET 2
E. value2 = “h”; instead of // CODE SNIPPET 2
F. value3 = “i”; instead of // CODE SNIPPET 2

A

B, C, E. value1 is a final instance variable. It can only be set once: in the variable declaration, an instance initializer, or a constructor. Option A does not compile because
the final variable was already set in the declaration. value2 is a static variable. Both
instance and static initializers are able to access static variables, making options B
and E correct. value3 is an instance variable. Options D and F do not compile because
a static initializer does not have access to instance variables.

107
Q

Which of the following are true about the following code? (Choose all that apply)
public class Create {
Create() {
System.out.print(“1 “);
}
Create(int num) {
System.out.print(“2 “);
}
Create(Integer num) {
System.out.print(“3 “);
}
Create(Object num) {
System.out.print(“4 “);
}
Create(int… nums) {
System.out.print(“5 “);
}
public static void main(String[] args) {
new Create(100);
new Create(1000L);
}
}
A. The code prints out 2 4.
B. The code prints out 3 4.
C. The code prints out 4 2.
D. The code prints out 4 4.
E. The code prints 3 4 if you remove the constructor Create(int num).
F. The code prints 4 4 if you remove the constructor Create(int num).
G. The code prints 5 4 if you remove the constructor Create(int num).

A

A, E. The 100 parameter is an int and so calls the matching int constructor. When
this constructor is removed, Java looks for the next most specific constructor. Java prefers autoboxing to varargs, and so chooses the Integer constructor. The 100L parameter is a long. Since it can’t be converted into a smaller type, it is autoboxed into a Long
and then the constructor for Object is called.

108
Q

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, Predicate<Panda> pred) {
11: String result = pred.test(panda) ? "match" : "not match";
12: System.out.print(result);
13: } }
A. match
B. not match
C. Compiler error on line 8.
D. Compiler error on line 10.
E. Compiler error on line 11.
F. A runtime exception is thrown.</Panda>

A

A. This code is correct. Line 8 creates a lambda expression that checks if the age is less
than 5. Since there is only one parameter and it does not specify a type, the parentheses
around the type parameter are optional. Line 10 uses the Predicate interface, which
declares a test() method.

109
Q

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, l) -> h.append(l).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: else
13: System.out.println(“ok”);
14: }
15: }
A. ok
B. too high
C. Compiler error on line 7.
D. Compiler error on line 10.
E. Compiler error on a different line.
F. A runtime exception is thrown

A

C. The interface takes two int parameters. The code on line 7 attempts to use them as
if one is a StringBuilder. It is tricky to use types in a lambda when they are implicitly
specified. Remember to check the interface for the real type.

110
Q

Which of the following lambda expressions can fill in the blank? (Choose all that apply)
List<String> list = new ArrayList<>();
list.removeIf(\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_);
A. s -> s.isEmpty()
B. s -> {s.isEmpty()}
C. s -> {s.isEmpty();}
D. s -> {return s.isEmpty();}
E. String s -> s.isEmpty()
F. (String s) -> s.isEmpty()</String>

A

A, D, F. removeIf() expects a Predicate, which takes a parameter list of one parameter using the specified type. Options B and C are incorrect because they do not use the
return keyword. It is required inside braces for lambda bodies. Option E is incorrect
because it is missing the parentheses around the parameter list. This is only optional
for a single parameter with an inferred type.

111
Q

Which lambda can replace the MySecret class to return the same value? (Choose
all that apply)
interface Secret {
String magic(double d);
}
class MySecret implements Secret {
public String magic(double d) {
return “Poof”;
}
}
A. caller((e) -> “Poof”);
B. caller((e) -> {“Poof”});
C. caller((e) -> { String e = “”; “Poof” });
D. caller((e) -> { String e = “”; return “Poof”; });
E. caller((e) -> { String e = “”; return “Poof” });
F. caller((e) -> { String f = “”; return “Poof”; });

A

A, F. Option B is incorrect because it does not use the return keyword. Options C, D,
and E are incorrect because the variable e is already in use from the lambda and cannot be redefined. Additionally, option C is missing the return keyword and option E is
missing the semicolon.

112
Q

What modifiers are implicitly applied to all interface methods? (Choose all that apply)
A. protected
B. public
C. static
D. void
E. abstract
F. default

A

B. All interface methods are implicitly public, so option B is correct and option A is
not. Interface methods may be declared as static or default but are never implicitly
added, so options C and F are incorrect. Option D is incorrect—void is not a modifier;
it is a return type. Option E is a tricky one, because prior to Java 8 all interface methods would be assumed to be abstract. Since Java 8 now includes default and static
methods and they are never abstract, you cannot assume the abstract modifier will be
implicitly applied to all methods by the compiler.

113
Q

What is the output of the following code?
1: class Mammal {
2: public Mammal(int age) {
3: System.out.print(“Mammal”);
4: }
5: }
6: public class Platypus extends Mammal {
7: public Platypus() {
8: System.out.print(“Platypus”);
9: }
10: public static void main(String[] args) {
11: new Mammal(5);
12: }
13: }
A. Platypus
B. Mammal
C. PlatypusMammal
D. MammalPlatypus
E. The code will not compile because of line 8.
F. The code will not compile because of line 11.

A

E. The code will not compile because the parent class Mammal doesn’t define a no-argument constructor, so the first line of a Platypus constructor should be an explicit call
to super(int age). If there was such a call, then the output would be MammalPlatypus,
since the super constructor is executed before the child constructor.

114
Q

Which of the following statements can be inserted in the blank line so that the code will
compile successfully? (Choose all that apply)
public interface CanHop {}
public class Frog implements CanHop {
public static void main(String[] args) {
frog = new TurtleFrog();
}
}
public class BrazilianHornedFrog extends Frog {}
public class TurtleFrog extends Frog {}
A. Frog
B. TurtleFrog
C. BrazilianHornedFrog
D. CanHop
E. Object
F. Long

A

A, B, D, E. The blank can be filled with any class or interface that is a supertype of
TurtleFrog. Option A is a superclass of TurtleFrog, and option B is the same class,
so both are correct. BrazilianHornedFrog is not a superclass of TurtleFrog, so option
C is incorrect. TurtleFrog inherits the CanHope interface, so option D is correct. All
classes inherit Object, so option E is correct. Finally, Long is an unrelated class that is
not a superclass of TurtleFrog, and is therefore incorrect

115
Q

Which statement(s) are correct about the following code? (Choose all that apply)
public class Rodent {
protected static Integer chew() throws Exception {
System.out.println(“Rodent is chewing”);
return 1;
}
}
public class Beaver extends Rodent {
public Number chew() throws RuntimeException {
System.out.println(“Beaver is chewing on wood”);
return 2;
}
}
A. It will compile without issue.
B. It fails to compile because the type of the exception the method throws is a subclass of
the type of exception the parent method throws.
C. It fails to compile because the return types are not covariant.
D. It fails to compile because the method is protected in the parent class and public in
the subclass.
E. It fails to compile because of a static modifier mismatch between the two methods.

A

C, E. The code doesn’t compile, so option A is incorrect. Option B is also not correct
because the rules for overriding a method allow a subclass to define a method with an exception that is a subclass of the exception in the parent method. Option C is correct because the return types are not covariant; in particular, Number is not a subclass of Integer. Option D is incorrect because the subclass defines a method that is more accessible than the method in the parent class, which is allowed. Finally, option E is correct because the method is declared as static in the parent class and not so in the child class. For nonprivate methods in the parent class, both methods must use static (hide) or neither should use static (override).

116
Q

Which of the following may only be hidden and not overridden? (Choose all that apply)
A. private instance methods
B. protected instance methods
C. public instance methods
D. static methods
E. public variables
F. private variables

A

A, D, E, F. First off, options B and C are incorrect because protected and public methods may be overridden, not hidden. Option A is correct because private methods are
always hidden in a subclass. Option D is also correct because static methods cannot
be overridden, only hidden. Options E and F are correct because variables may only be
hidden, regardless of the access modifier.

117
Q

Choose the correct statement about the following code:
1: interface HasExoskeleton {
2: abstract int getNumberOfSections();
3: }
4: abstract class Insect implements HasExoskeleton {
5: abstract int getNumberOfLegs();
6: }
7: public class Beetle extends Insect {
8: int getNumberOfLegs() { return 6; }
9: }
A. It compiles and runs without issue.
B. The code will not compile because of line 2.
C. The code will not compile because of line 4.
D. The code will not compile because of line 7.
E. It compiles but throws an exception at runtime.

A

D. The code fails to compile because Beetle, the first concrete subclass, doesn’t implement getNumberOfSections(), which is inherited as an abstract method; therefore,
option D is correct. Option B is incorrect because there is nothing wrong with this
interface method definition. Option C is incorrect because an abstract class is not required to implement any abstract methods, including those inherited from an interface. Option E is incorrect because the code fails at compilation-time.

118
Q

Which of the following statements about polymorphism are true? (Choose all that apply)
A. A reference to an object may be cast to a subclass of the object without an explicit cast.
B. If a method takes a superclass of three objects, then any of those classes may be passed
as a parameter to the method.
C. A method that takes a parameter with type java.lang.Object will take any reference.
D. All cast exceptions can be detected at compile-time.
E. By defining a public instance method in the superclass, you guarantee that the specific
method will be called in the parent class at runtime.

A

B, C. A reference to an object requires an explicit cast if referenced with a subclass,
so option A is incorrect. If the cast is to a superclass reference, then an explicit cast is not required. Because of polymorphic parameters, if a method takes the superclass of an object as a parameter, then any subclass references may be used without a cast, so option B is correct. All objects extend java.lang.Object, so if a method takes that
type, any valid object, including null, may be passed; therefore, option C is correct. Some cast exceptions can be detected as errors at compile-time, but others can only be detected at runtime, so D is incorrect. Due to the nature of polymorphism, a public
instance method can be overridden in a subclass and calls to it will be replaced even in the superclass it was defined, so E is incorrect.

119
Q

Choose the correct statement about the following code:
1: public interface Herbivore {
2: int amount = 10;
3: public static void eatGrass();
4: public int chew() {
5: return 13;
6: }
7: }
A. It compiles and runs without issue.
B. The code will not compile because of line 2.
C. The code will not compile because of line 3.
D. The code will not compile because of line 4.
E. The code will not compile because of lines 2 and 3.
F. The code will not compile because of lines 3 and 4.

A

F. The interface variable amount is correctly declared, with public and static being
assumed and automatically inserted by the compiler, so option B is incorrect. The
method declaration for eatGrass() on line 3 is incorrect because the method has been
marked as static but no method body has been provided. The method declaration for
chew() on line 4 is also incorrect, since an interface method that provides a body must be marked as default or static explicitly. Therefore, option F is the correct answer since this code contains two compile-time errors.

120
Q

Choose the correct statement about the following code:
1: public interface CanFly {
2: void fly();
3: }
4: interface HasWings {
5: public abstract Object getWindSpan();
6: }
7: abstract class Falcon implements CanFly, HasWings {
8: }
A. It compiles without issue.
B. The code will not compile because of line 2.
C. The code will not compile because of line 4.
D. The code will not compile because of line 5.
E. The code will not compile because of lines 2 and 5.
F. The code will not compile because the class Falcon doesn’t implement the interface
methods.

A

A. Although the definition of methods on lines 2 and 5 vary, both will be converted to public abstract by the compiler. Line 4 is fine, because an interface can have public or default access. Finally, the class Falcon doesn’t need to implement the interface
methods because it is marked as abstract. Therefore, the code will compile without
issue.

121
Q

Which statements are true for both abstract classes and interfaces? (Choose all that apply)
A. All methods within them are assumed to be abstract.
B. Both can contain public static final variables.
C. Both can be extended using the extend keyword.
D. Both can contain default methods.
E. Both can contain static methods.
F. Neither can be instantiated directly.
G. Both inherit java.lang.Object.

A

B, C, E, F. Option A is wrong, because an abstract class may contain concrete methods. Since Java 8, interfaces may also contain concrete methods in form of static or
default methods. Although all variables in interfaces are assumed to be public static
final, abstract classes may contain them as well, so option B is correct. Both abstract
classes and interfaces can be extended with the extends keyword, so option C is correct. Only interfaces can contain default methods, so option D is incorrect. Both
abstract classes and interfaces can contain static methods, so option E is correct. Both
structures require a concrete subclass to be instantiated, so option F is correct. Finally,
though an instance of an object that implements an interface inherits java.lang.
Object, the interface itself doesn’t; otherwise, Java would support multiple inheritance
for objects, which it doesn’t. Therefore, option G is incorrect.

122
Q

What modifiers are assumed for all interface variables? (Choose all that apply)
A. public
B. protected
C. private
D. static
E. final
F. abstract

A

A, D, E. Interface variables are assumed to be public static final; therefore, options
A, D, and E are correct. Options B and C are incorrect because interface variables must
be public—interfaces are implemented by classes, not inherited by interfaces. Option F
is incorrect because variables can never be abstract.

123
Q

What is the output of the following code?
1: interface Nocturnal {
2: default boolean isBlind() { return true; }
3: }
4: public class Owl implements Nocturnal {
5: public boolean isBlind() { return false; }
6: public static void main(String[] args) {
7: Nocturnal nocturnal = (Nocturnal)new Owl();
8: System.out.println(nocturnal.isBlind());
9: }
10: }
A. true
B. false
C. The code will not compile because of line 2.
D. The code will not compile because of line 5.
E. The code will not compile because of line 7.
F. The code will not compile because of line 8.

A

B. This code compiles and runs without issue, outputting false, so option B is the correct answer. The first declaration of isBlind() is as a default interface method, assumed public. The second declaration of isBlind() correctly overrides the default interface method. Finally, the newly created Owl instance may be automatically cast to
a Nocturnal reference without an explicit cast, although adding it doesn’t break the
code

124
Q

What is the output of the following code?
1: class Arthropod
2: public void printName(double input) { System.out
.print(“Arthropod”); }
3: }
4: public class Spider extends Arthropod {
5: public void printName(int input) { System.out.print(“Spider”); }
6: public static void main(String[] args) {
7: Spider spider = new Spider();
8: spider.printName(4);
9: spider.printName(9.0);
10: }
11: }
A. SpiderArthropod
B. ArthropodSpider
C. SpiderSpider
D. ArthropodArthropod
E. The code will not compile because of line 5.
F. The code will not compile because of line 9.

A

A. The code compiles and runs without issue, so options E and F are incorrect. The
printName() method is an overload in Spider, not an override, so both methods may be called. The call on line 8 references the version that takes an int as input defined in the Spider class, and the call on line 9 references the version in the Arthropod class that takes a double. Therefore, SpiderArthropod is output and option A is the correct
answer.

125
Q

Which statements are true about the following code? (Choose all that apply)
1: interface HasVocalCords {
2: public abstract void makeSound();
3: }
4: public interface CanBark extends HasVocalCords {
5: public void bark();
6: }
A. The CanBark interface doesn’t compile.
B. A class that implements HasVocalCords must override the makeSound() method.
C. A class that implements CanBark inherits both the makeSound() and bark() methods.
D. A class that implements CanBark only inherits the bark() method.
E. An interface cannot extend another interface.

A

C. The code compiles without issue, so option A is wrong. Option B is incorrect, since an abstract class could implement HasVocalCords without the need to override the makeSound() method. Option C is correct; any class that implements CanBark automatically inherits its methods, as well as any inherited methods defined in the parent interface. Because option C is correct, it follows that option D is incorrect. Finally, an interface can extend multiple interfaces, so option E is incorrect.

126
Q

Which of the following is true about a concrete subclass? (Choose all that apply)
A. A concrete subclass can be declared as abstract.
B. A concrete subclass must implement all inherited abstract methods.
C. A concrete subclass must implement all methods defined in an inherited interface.
D. A concrete subclass cannot be marked as final.
E. Abstract methods cannot be overridden by a concrete subclass.

A

B. Concrete classes are, by definition, not abstract, so option A is incorrect. A concrete class must implement all inherited abstract methods, so option B is correct. Option C is incorrect; a superclass may have already implemented an inherited interface, so the
concrete subclass would not need to implement the method. Concrete classes can be both final and not final, so option D is incorrect. Finally, abstract methods must be overridden by a concrete subclass, so option E is incorrect.

127
Q

What is the output of the following code?
1: abstract class Reptile {
2: public final void layEggs() { System.out.println(“Reptile laying eggs”);
}
3: public static void main(String[] args) {
4: Reptile reptile = new Lizard();
5: reptile.layEggs();
6: }
7: }
8: public class Lizard extends Reptile {
9: public void layEggs() { System.out.println(“Lizard laying eggs”); }
10: }
A. Reptile laying eggs
B. Lizard laying eggs
C. The code will not compile because of line 4.
D. The code will not compile because of line 5.
E. The code will not compile because of line 9.

A

E. The code doesn’t compile, so options A and B are incorrect. The issue with line 9 is that layEggs() is marked as final in the superclass Reptile, which means it cannot be
overridden. There are no errors on any other lines, so options C and D are incorrect.

128
Q

What is the output of the following code?
1: public abstract class Whale {
2: public abstract void dive() {};
3: public static void main(String[] args) {
4: Whale whale = new Orca();
5: whale.dive();
6: }
7: }
8: class Orca extends Whale {
9: public void dive(int depth) { System.out.println(“Orca diving”); }
10: }
A. Orca diving
B. The code will not compile because of line 2.
C. The code will not compile because of line 8.
D. The code will not compile because of line 9.
E. The output cannot be determined from the code provided.

A

B. This may look like a complex question, but it is actually quite easy. Line 2 contains
an invalid definition of an abstract method. Abstract methods cannot contain a body,
so the code will not compile and option B is the correct answer. If the body {} was
removed from line 2, the code would still not compile, although it would be line 8 that
would throw the compilation error. Since dive() in Whale is abstract and Orca extends
Whale, then it must implement an overridden version of dive(). The method on line
9 is an overloaded version of dive(), not an overridden version, so Orca is an invalid
subclass and will not compile

129
Q

What is the output of the following code? (Choose all that apply)
1: interface Aquatic {
2: public default int getNumberOfGills(int input) { return 2; }
3: }
4: public class ClownFish implements Aquatic {
5: public String getNumberOfGills() { return “4”; }
6: public String getNumberOfGills(int input) { return “6”; }
7: public static void main(String[] args) {
8: System.out.println(new ClownFish().getNumberOfGills(-1));
9: }
10: }
A. 2
B. 4
C. 6
D. The code will not compile because of line 5.
E. The code will not compile because of line 6.
F. The code will not compile because of line 8.

A

E. The code doesn’t compile because line 6 contains an incompatible override of the
getNumberOfGills(int input) method defined in the Aquatic interface. In particular,
int and String are not covariant returns types, since int is not a subclass of String.
Note that line 5 compiles without issue; getNumberOfGills() is an overloaded method
that is not related to the parent interface method that takes an int value

130
Q

Which of the following statements can be inserted in the blank so that the code will
compile successfully? (Choose all that apply)
public class Snake {}
public class Cobra extends Snake {}
public class GardenSnake {}
public class SnakeHandler {
private Snake snake;
public void setSnake(Snake snake) { this.snake = snake; }
public static void main(String[] args) {
new SnakeHandler().setSnake( );
}
}
A. new Cobra()
B. new GardenSnake()
C. new Snake()
D. new Object()
E. new String(“Snake”)
F. null

A

A, C, F. First off, Cobra is a subclass of Snake, so option A can be used. GardenSnake is
not defined as a subclass of Snake, so it cannot be used and option B is incorrect. The
class Snake is not marked as abstract, so it can be instantiated and passed, so option
C is correct. Next, Object is a superclass of Snake, not a subclass, so it also cannot be
used and option D is incorrect. The class String is unrelated in this example, so option
E is incorrect. Finally, a null value can always be passed as an object value, regardless
of type, so option F is correct.

131
Q

What is the result of the following code?
1: public abstract class Bird {
2: private void fly() { System.out.println(“Bird is flying”); }
3: public static void main(String[] args) {
4: Bird bird = new Pelican();
5: bird.fly();
6: }
7: }
8: class Pelican extends Bird {
9: protected void fly() { System.out.println(“Pelican is flying”); }
10: }
A. Bird is flying
B. Pelican is flying
C. The code will not compile because of line 4.
D. The code will not compile because of line 5.
E. The code will not compile because of line 9.

A

. A. The code compiles and runs without issue, so options C, D, and E are incorrect.
The trick here is that the method fly() is marked as private in the parent class Bird,
which means it may only be hidden, not overridden. With hidden methods, the specific
method used depends on where it is referenced. Since it is referenced within the Bird
class, the method declared on line 2 was used, and option A is correct. Alternatively,
if the method was referenced within the Pelican class, or if the method in the parent
class was marked as protected and overridden in the subclass, then the method on line
9 would have been used.

132
Q

Which of the following statements are true? (Choose all that apply)
A. Runtime exceptions are the same thing as checked exceptions.
B. Runtime exceptions are the same thing as unchecked exceptions.
C. You can declare only checked exceptions.
D. You can declare only unchecked exceptions.
E. You can handle only Exception subclasses.

A

B. Runtime exceptions are also known as unchecked exceptions. They are allowed
to be declared, but they don’t have to be. Checked exceptions must be handled or declared. Legally, you can handle java.lang.Error subclasses, but it’s not a good idea.

133
Q

Which of the following pairs fill in the blanks to make this code compile? (Choose all that
apply)
7: public void ohNo() _____ Exception {
8: _____________ Exception();
9: }
A. On line 7, fill in throw
B. On line 7, fill in throws
C. On line 8, fill in throw
D. On line 8, fill in throw new
E. On line 8, fill in throws
F. On line 8, fill in throws new

A

B, D. In a method declaration, the keyword throws is used. To actually throw an
exception, the keyword throw is used and a new exception is created.

134
Q

When are you required to use a finally block in a regular try statement (not a try-withresources)?
A. Never.
B. When the program code doesn’t terminate on its own.
C. When there are no catch blocks in a try statement.
D. When there is exactly one catch block in a try statement.
E. When there are two or more catch blocks in a try statement.

A

C. A try statement is required to have a catch clause and/or finally clause. If it goes
the catch route, it is allowed to have multiple catch clauses.

135
Q

Which exception will the following throw?
Object obj = new Integer(3);
String str = (String) obj;
System.out.println(str);
A. ArrayIndexOutOfBoundsException
B. ClassCastException
C. IllegalArgumentException
D. NumberFormatException
E. None of the above.

A

B. The second line tries to cast an Integer to a String. Since String does not extend
Integer, this is not allowed and a ClassCastException is thrown.

136
Q

Which of the following exceptions are thrown by the JVM? (Choose all that apply)
A. ArrayIndexOutOfBoundsException
B. ExceptionInInitializerError
C. java.io.IOException
D. NullPointerException
E. NumberFormatException

A

A, B, D. java.io.IOException is thrown by many methods in the java.io package,
but it is always thrown programmatically. The same is true for NumberFormatException; it is thrown programmatically by the wrapper classes of java.lang. The other
three exceptions are all thrown by the JVM when the corresponding problem arises.

137
Q

What will happen if you add the statement System.out.println(5 / 0); to a working
main() method?
A. It will not compile.
B. It will not run.
C. It will run and throw an ArithmeticException.
D. It will run and throw an IllegalArgumentException.
E. None of the above.

A

C. The compiler tests the operation for a valid type but not a valid result, so the code will still compile and run. At runtime, evaluation of the parameter takes place before passing it to the print() method, so an ArithmeticException object is raised.

138
Q

What is printed besides the stack trace caused by the NullPointerException from line 16?
1: public class DoSomething {
2: public void go() {
3: System.out.print(“A”);
4: try {
5: stop();
6: } catch (ArithmeticException e) {
7: System.out.print(“B”);
8: } finally {
9: System.out.print(“C”);
10: }
11: System.out.print(“D”);
12: }
13: public void stop() {
14: System.out.print(“E”);
15: Object x = null;
16: x.toString();
17: System.out.print(“F”);
18: }
19: public static void main(String[] args) {
20: new DoSomething().go();
21: }
22: }
A. AE
B. AEBCD
C. AEC
D. AECD
E. No output appears other than the stack trace.

A

C. The main() method invokes go and A is printed on line 3. The stop method is
invoked and E is printed on line 14. Line 16 throws a NullPointerException, so stop
immediately ends and line 17 doesn’t execute. The exception isn’t caught in go, so the
go method ends as well, but not before its finally block executes and C is printed on
line 9. Because main() doesn’t catch the exception, the stack trace displays and no further output occurs, so AEC was the output printed before the stack trace.

139
Q

What is the output of the following snippet, assuming a and b are both 0?
3: try {
4: return a / b;
5: } catch (RuntimeException e) {
6: return -1;
7: } catch (ArithmeticException e) {
8: return 0;
9: } finally {
10: System.out.print(“done”);
11: }
A. -1
B. 0
C. done-1
D. done0
E. The code does not compile.
F. An uncaught exception is thrown.

A

E. The order of catch blocks is important because they’re checked in the order they
appear after the try block. Because ArithmeticException is a child class of RuntimeException, the catch block on line 7 is unreachable. (If an ArithmeticException is
thrown in try try block, it will be caught on line 5.) Line 7 generates a compiler error
because it is unreachable code

140
Q

What is the output of the following program?
1: public class Laptop {
2: public void start() {
3: try {
4: System.out.print(“Starting up “);
5: throw new Exception();
6: } catch (Exception e) {
7: System.out.print(“Problem “);
8: System.exit(0);
9: } finally {
10: System.out.print(“Shutting down “);
11: }
12: }
13: public static void main(String[] args) {
14: new Laptop().start();
15: } }
A. Starting up
B. Starting up Problem
C. Starting up Problem Shutting down
D. Starting up Shutting down
E. The code does not compile.
F. An uncaught exception is thrown.

A

B. The main() method invokes start on a new Laptop object. Line 4 prints Starting up; then line 5 throws an Exception. Line 6 catches the exception, line 7 prints Problem, and then line 8 calls System.exit, which terminates the JVM. The finally block does not execute because the JVM is no longer running.

141
Q

What is the output of the following program?
1: public class Dog {
2: public String name;
3: public void parseName() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: int x = Integer.parseInt(name);
8: System.out.print(“3”);
9: } catch (NumberFormatException e) {
10: System.out.print(“4”);
11: }
12: }
13: public static void main(String[] args) {
14: Dog leroy = new Dog();
15: leroy.name = “Leroy”;
16: leroy.parseName();
17: System.out.print(“5”);
18: } }
A. 12
B. 1234
C. 1235
D. 124
E. 1245
F. The code does not compile.
G. An uncaught exception is thrown.

A

E. The parseName method is invoked within main() on a new Dog object. Line 4 prints
1. The try block executes and 2 is printed. Line 7 throws a NumberFormatException, so
line 8 doesn’t execute. The exception is caught on line 9, and line 10 prints 4. Because the exception is handled, execution resumes normally. parseName runs to completion, and
line 17 executes, printing 5. That’s the end of the program, so the output is 1245.

142
Q

What is the output of the following program?
1: public class Cat {
2: public String name;
3: public void parseName() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: int x = Integer.parseInt(name);
8: System.out.print(“3”);
9: } catch (NullPointerException e) {
10: System.out.print(“4”);
11: }
12: System.out.print(“5”);
13: }
14: public static void main(String[] args) {
15: Cat leo = new Cat();
16: leo.name = “Leo”;
17: leo.parseName();
18: System.out.print(“6”);
19: }
20: }
A. 12, followed by a stack trace for a NumberFormatException
B. 124, followed by a stack trace for a NumberFormatException
C. 12456
D. 12456
E. 1256, followed by a stack trace for a NumberFormatException
F. The code does not compile.
G. An uncaught exception is thrown.

A

A. The parseName method is invoked on a new Cat object. Line 4 prints 1. The try
block is entered, and line 6 prints 2. Line 7 throws a NumberFormatException. It isn’t
caught, so parseName ends. main() doesn’t catch the exception either, so the program
terminates and the stack trace for the NumberFormatException is printed.

143
Q

What is printed by the following? (Choose all that apply)
1: public class Mouse {
2: public String name;
3: public void run() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: name.toString();
8: System.out.print(“3”);
9: } catch (NullPointerException e) {
10: System.out.print(“4”);
11: throw e;
12: }
13: System.out.print(“5”);
14: }
15: public static void main(String[] args) {
16: Mouse jerry = new Mouse();
17: jerry.run();
18: System.out.print(“6”);
19: } }
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
G. The stack trace for a NullPointerException

A

A, B, D, G. The main() method invokes run on a new Mouse object. Line 4 prints 1 and
line 6 prints 2, so options A and B are correct. Line 7 throws a NullPointerException,
which causes line 8 to be skipped, so C is incorrect. The exception is caught on line 9 and line 10 prints 4, so option D is correct. Line 11 throws the exception again, which causes run() to immediately end, so line 13 doesn’t execute and option E is incorrect.
The main() method doesn’t catch the exception either, so line 18 doesn’t execute and option F is incorrect. The uncaught NullPointerException causes the stack trace to be
printed, so option G is correct.

144
Q

Which of the following statements are true? (Choose all that apply)
A. You can declare a method with Exception as the return type.
B. You can declare any subclass of Error in the throws part of a method declaration.
C. You can declare any subclass of Exception in the throws part of a method
declaration.
D. You can declare any subclass of Object in the throws part of a method declaration.
E. You can declare any subclass of RuntimeException in the throws part of a method
declaration.

A

A, B, C, E. Classes listed in the throws part of a method declaration must extend
java.lang.Throwable. This includes Error, Exception, and RuntimeException. Arbitrary classes such as String can’t go there. Any Java type, including Exception, can
be declared as the return type. However, this will simply return the object rather than
throw an exception.

145
Q

Which of the following can be inserted on line 8 to make this code compile? (Choose all
that apply)
7: public void ohNo() throws IOException {
8: // INSERT CODE HERE
9: }
A. System.out.println(“it’s ok”);
B. throw new Exception();
C. throw new IllegalArgumentException();
D. throw new java.io.IOException();
E. throw new RuntimeException();

A

A, C, D, E. A method that declares an exception isn’t required to throw one, making
option A correct. Runtime exceptions can be thrown in any method, making options
C and E correct. Option D matches the exception type declared and so is also correct.
Option B is incorrect because a broader exception is not allowed.

146
Q

Which of the following are unchecked exceptions? (Choose all that apply)
A. ArrayIndexOutOfBoundsException
B. IllegalArgumentException
C. IOException
D. NumberFormatException
E. Any exception that extends RuntimeException
F. Any exception that extends Exception

A

A, B, D, E. ArrayIndexOutOfBoundsException, IllegalArgumentException, and NumberFormatException are runtime exceptions. Sorry, you have to memorize them. Any class that extends RuntimeException is a runtime (unchecked) exception. Classes that
extend Exception but not RuntimeException are checked exceptions.

147
Q

Which scenario is the best use of an exception?
A. An element is not found when searching a list.
B. An unexpected parameter is passed into a method.
C. The computer caught fire.
D. You want to loop through a list.
E. You don’t know how to code a method.

A

B. IllegalArgumentException is used when an unexpected parameter is passed into a
method. Option A is incorrect because returning null or -1 is a common return value
for this scenario. Option D is incorrect because a for loop is typically used for this
scenario. Option E is incorrect because you should find out how to code the method
and not leave it for the unsuspecting programmer who calls your method. Option C is
incorrect because you should run!

148
Q

Which of the following can be inserted into Lion to make this code compile? (Choose all
that apply)
class HasSoreThroatException extends Exception {}
class TiredException extends RuntimeException {}
interface Roar {
void roar() throws HasSoreThroatException;
}
class Lion implements Roar {// INSERT CODE HERE
}
A. public void roar(){}
B. public void roar() throws Exception{}
C. public void roar() throws HasSoreThroatException{}
D. public void roar() throws IllegalArgumentException{}
E. public void roar() throws TiredException{}

A

A, C, D, E. The method is allowed to throw no exceptions at all, making option A correct. It is also allowed to throw runtime exceptions, making options D and E correct.
Option C is also correct since it matches the signature in the interface

149
Q

Which of the following are true? (Choose all that apply)
A. Checked exceptions are allowed to be handled or declared.
B. Checked exceptions are required to be handled or declared.
C. Errors are allowed to be handled or declared.
D. Errors are required to be handled or declared.
E. Runtime exceptions are allowed to be handled or declared.
F. Runtime exceptions are required to be handled or declared.

A

A, B, C, E. Checked exceptions are required to be handled or declared. Runtime exceptions are allowed to be handled or declared. Errors are allowed to be handled or
declared, but this is bad practice.

150
Q

Which of the following can be inserted in the blank to make the code compile? (Choose all
that apply)
public static void main(String[] args) {
try {
System.out.println(“work real hard”);
} catch ( e) {
} catch (RuntimeException e) {
}
}
A. Exception
B. IOException
C. IllegalArgumentException
D. RuntimeException
E. StackOverflowError
F. None of the above.

A

C, E. Option C is allowed because it is a more specific type than RuntimeException.
Option E is allowed because it isn’t in the same inheritance tree as RuntimeException. It’s not a good idea to catch either of these. Option B is not allowed because the
method called inside the try block doesn’t declare an IOException to be thrown. The compiler realizes that IOException would be an unreachable catch block. Option D is not allowed because the same exception can’t be specified in two different catch
blocks. Finally, option A is not allowed because it’s more general than RuntimeException and would make that block unreachable.

151
Q

What does the output of the following contain? (Choose all that apply)
12: public static void main(String[] args) {
13: System.out.print(“a”);
14: try {
15: System.out.print(“b”);
16: throw new IllegalArgumentException();
17: } catch (IllegalArgumentException e) {
18: System.out.print(“c”);
19: throw new RuntimeException(“1”);
20: } catch (RuntimeException e) {
21: System.out.print(“d”);
22: throw new RuntimeException(“2”);
23: } finally {
24: System.out.print(“e”);
25: throw new RuntimeException(“3”);
26: }
27: }
A. abce
B. abde
C. An exception with the message set to “1”
D. An exception with the message set to “2”
E. An exception with the message set to “3”
F. Nothing; the code does not compile.

A

A, E. The code begins normally and prints a on line 13, followed by b on line 15. On
line 16, it throws an exception that’s caught on line 17. Remember, only the most specific matching catch is run. Line 18 prints c, and then line 19 throws another exception. Regardless, the finally block runs, printing e. Since the finally block also
throws an exception, that’s the one printed.