1: enum Color {
2: public static Color DEFAULT = BROWN;
3: BROWN, YELLOW, BLACK;
4: }
5: public record Pony {
6: String name;
7: static int age;
8: { age = 10;}
9: }
nonsealed
default
sealed
unsealed
non-sealed
closed
final
package dnd;
final class Story {
void recite(int chapter) throws Exception {}
}
public class Adventure extends Story {
final void recite(final int chapter) { // g1
switch(chapter) { // g2
case 2: System.out.print(9);
default: System.out.print(3);
}
}
public static void main(String… u) {
var bedtime = new Adventure();
bedtime.recite(2);
} }
3
9
93
g1
.g2
.import widget.*;
// Widget Manager
int facilityNumber;
package sprockets;
/** Author: Cid **/
void produce() {}
final
private
public
default
protected
concrete
1: public class ParkRanger {
2: final static int birds = 10;
3: public static void main(String[] data) {
4: var r = new ParkRanger();
5: var trees = 5f;
6: System.out.print(trees + r.birds);
7: } }
5
.5.0
.15
.15.0
.protected
private
, packageprivate
, protected
private
, public
public
, private
default
method within an interface, prevents it from being overridden by a class implementing the interface?
const
final
static
private
private static
package competition;
public class Robot {
static String weight = "A lot";
double ageMonths = 5, ageDays = 2;
private static boolean success = true;
public void compete() {
final String retries = "1";
// P1
} }
Variable Type | Number of Variables Accessible at P1 |
---|---|
Class | _____ |
Instance | _____ |
Local | _____ |
_____________ agent;
public _____________ Banker {
private static _____________ getMaxWithdrawal() {
return 10;
} }
package
, new
, int
package
, class
, long
import
, class
, null
//
, class
, int
import
, interface
, void
package
, class
, void
public class Phone {
private int size;
// LINE X
public static void sendHome(Phone p, int newSize) {
p = new Phone(newSize);
p.size = 4;
}
public static final void main(String… params) {
final var phone = new Phone(3);
sendHome(phone,7);
System.out.print(phone.size);
} }
LINE X
:
public static Phone create(int size) {
return new Phone(size);
}
LINE X
:
public static Phone newInstance(int size) {
return new Phone();
}
LINE X
:
public Phone(int size) {
size = this.size;
}
LINE X
:
public void Phone(int size) {
size = this.size;
}
0
.3
.7
.public class Dinosaur {
class Pterodactyl extends Dinosaur {}
public void roar() {
var dino = new Dinosaur();
____________________________;
} }
dino.Pterodactyl()
Dinosaur.new Pterodactyl()
dino.new Pterodactyl()
new Dino().new Pterodactyl()
new Dinosaur().Pterodactyl()
new Dinosaur.Pterodactyl()
Computer
program?
class Laptop extends Computer {
public void startup() {
System.out.print("laptop-");
} }
public class Computer {
public void startup() {
System.out.print("computer-");
}
public static void main(String[] args) {
Computer computer = new Laptop();
Laptop laptop = new Laptop();
computer.startup();
laptop.startup();
} }
computer-laptop-
laptop-computer-
laptop-laptop-
public class Cars {
private static void drive() {
{
System.out.println("zoom");
}
System.out.println("fast");
}
static { System.out.println("faster"); }
public static void main(String[] args) {
drive();
drive();
} }
static
interface methods are correct? (Choose three.)
static
interface method can be final
.static
interface method can be declared private
.static
interface method can be declared with package access.static
interface method can be declared public
.static
interface method can be declared protected
.static
interface method can be declared without an access modifier.Planet
declaration, how many declarations compile? Assume they are all declared within the same .java
file.
public abstract sealed class Planet permits Mercury, Venus, Earth {}
non-sealed class Venus {}
non-sealed class Mars extends Planet {}
non-sealed class Mercury {}
abstract non-sealed class Earth {}
public class Canine {
public String woof(int bark) {
return "1"+bark.toString();
}
public String woof(Integer bark) {
return "2"+bark.toString();
}
public String woof(Object bark) {
return "3"+bark.toString();
}
public static void main(String[] a) {
System.out.println(woof((short)5));
} }
15
25
35
final.
static
variable that is marked final.
Turnip
class?
interface GameItem {
int sell();
}
abstract class Vegetable implements GameItem {
public final int sell() { return 5; }
}
public class Turnip extends Vegetable {
public final int sell() { return 3; }
public static void main(String[] expensive) {
System.out.print(new Turnip().sell());
} }
3
5
package holiday;
enum DaysOff {
Thanksgiving, PresidentsDay, ValentinesDay
}
public class Vacation {
public static void main(String[] unused) {
final DaysOff input = DaysOff.Thanksgiving;
switch(input) {
default:
case DaysOff.ValentinesDay:
System.out.print("1");
case DaysOff.PresidentsDay:
System.out.print("2");
} } }
1
2
12
record Animal(boolean isMammal) {}
public record Panda(String name) extends Animal {
public Panda() {
this("TaiShan");
}
public Panda {
this.name = name.toLowerCase();
}
public static void main(String[] args) {
System.out.print(new Panda().name());
} }
TaiShan
taishan
that
keyword can be used to read public
members in the direct parent class.this
keyword can be used to read all members declared within the class.super
keyword can be used to read all members declared in a parent class.that
keyword can be used to read members of another class.this
keyword can be used to read public
members in the direct parent class.super
keyword can be used in static
methods.abstract
class. An interface ______________ another interface.
extends
, extends
, implements
extends
, implements
, extends
extends
, implements
, implements
implements
, extends
, extends
implements
, extends
, implements
implements
, implements
, extends
c1
, c2
, and c3
, right before the end of the main()
method, assuming garbage collection hasn't run? In the diagrams, each box represents a Chicken
object with a number of eggs
.
1: public class Chicken {
2: private Integer eggs = 2;
3: { this.eggs = 3; }
4: public Chicken(int eggs) {
5: this.eggs = eggs;
6: }
7: public static void main(String[] r) {
8: var c1 = new Chicken(1);
9: var c2 = new Chicken(2);
10: var c3 = new Chicken(3);
11: c1.eggs = c2.eggs;
12: c2 = c1;
13: c3.eggs = null;
14: } }
package musical;
interface Speak { default int talk() { return 7; } }
interface Sing { default int talk() { return 5; } }
public class Performance implements Speak, Sing {
public int talk(String… x) {
return x.length;
}
public static void main(String[] notes) {
System.out.print(new Performance().talk());
} }
7
5
package ai;
interface Pump { public abstract String toString(); }
interface Bend extends Pump { void bend(double tensileStrength); }
public class Robot {
public static final void apply(
Bend instruction, double input) {
instruction.bend(input);
}
public static void main(String… future) {
final Robot r = new Robot();
r.apply(x -> System.out.print(x+" bent!"), 5);
} }
5 bent!
5.0 bent!
Bend
is not a functional interface.apply()
method declaration.private
and methods are private
.private
and methods are public
.public
and methods are private
.public
and methods are public
.private
and methods are protected
.public interface Swimming {
String DEFAULT = "Diving!"; // k1
abstract int breath();
private static void stroke() {
if(breath()==1) { // k2
System.out.print("Go!");
} else {
System.out.print(dive()); // k3
} }
static String dive() {
return DEFAULT; // k4
} }
k1
.k2
.k3
.k4
.class Tool {
private void repair() {} // r1
void use() {} // r2
}
class Hammer extends Tool {
private int repair() { return 0; } // r3
private void use() {} // r4
public void bang() {} // r5
}
r1
r2
r3
r4
r5
abstract
interface method?
final
interface
protected
volatile
sealed
Plant
program?
class Bush extends Plant {
String type = "bush";
}
public class Plant {
String type = "plant";
public static void main(String[] args) {
Plant w1 = new Bush();
Bush w2 = new Bush();
Plant w3 = w2;
System.out.print(w1.type+","+w2.type+","+w3.type);
} }
plant,bush,plant
plant,bush,bush
bush,plant,bush
bush,bush,bush
Organ
class is included, unmodified, in a larger program at runtime. At most, how many classes can inherit from Organ
(excluding Organ
itself)?
package body;
public sealed class Organ {
sealed class Heart extends Organ {}
final class Lung extends Organ {}
static non-sealed class Stomach extends Organ {}
final class Valentine extends Heart {}
}
import
statements, package
statement, class
declarationpackage
statement, class
declaration, import
statementsclass
declaration, import
statements, package
statementpackage
statement, import
statements, class
declarationimport
statements, class
declaration, package
statementclass
declaration, package
statement, import
statements1: class Penguin {
2: private enum Baby { EGG }
3: static class Chick {
4: enum Baby { EGG }
5: }
6: public static void main(String[] args) {
7: boolean match = false;
8: Baby egg = Baby.EGG;
9: switch (egg) {
10: case EGG:
11: match = true;
12: } } }
private
on line 2 would create an additional compiler error.private
on line 2 would not create an additional compiler error.static
modifier on line 3 would create an additional compiler error.static
modifier on line 3 would not create an additional compiler error.package beach;
public class Sand {
private static int numShovels;
private int numRakes;
public static int getNumShovels() {
return numShovels;
}
public static int getNumRakes() {
return numRakes;
}
public Sand() {
System.out.print("a");
}
public void Sand() {
System.out.print("b");
}
public void run() {
new Sand();
Sand();
}
public static void main(String… args) {
new Sand().run();
} }
a
.ab
.aab
.abstract
?
static
nested classabstract
.protected
public
protected
, packageprotected
, public
public
, packagepublic
, protected
var var = "var"; // line x1
var title = "Weather"; // line x2
var hot = 100, var cold = 20; // line x3
var f = 32, int c = 0; // line x4
x1
x2
x3
x4
Telephone
interface are public
?
public interface Telephone {
static int call() { return 1; }
default void dial() {}
long answer();
String home = "555-555-5555";
}
new
keyword does?
11: public class PrintShop {
12: public void printVarargs(String… names) {
13: System.out.println(Arrays.toString(names));
14: }
15: public void printArray(String[] names) {
16: System.out.println(Arrays.toString(names));
17: }
18: public void stormy() {
19: printVarargs("Arlene");
20: printVarargs(new String[]{"Bret"});
21: printVarargs(null);
22: printArray ("Cindy");
23: printArray (new String[]{"Don"});
24: printArray (null);
25: } }
final
modifier and set the instance variable directly.@FunctionalInterface
public interface Play {
public static void baseball() {}
private static void soccer() {}
default void play() {}
void fun();
}
static
method with the same signature as a static
method in a parent class is referred to as ___________________ a method.
public
.Secret
well encapsulated?
import java.util.*;
public class Secret {
private int number = new Random().nextInt(10);
public boolean guess(int candidate) {
return number == candidate;
} }
number
to use a protected
access modifier.number
to use a public
access modifier.private
constructor.public
constructor.guess
method.interface Toy { String play(); }
public class Gift {
public static void main(String[] matrix) {
abstract class Robot {}
class Transformer extends Robot implements Toy {
public String name = "GiantRobot";
public String play() {return "DinosaurRobot";} // y1
}
Transformer prime = new Transformer () {
public String play() {return name;} // y2
};
System.out.print(prime.play() + " " + name);
} }
GiantRobot
GiantRobot DinosaurRobot
DinosaurRobot
y1
.y2
.package space;
public class Bottle {
public static class Ship {
private enum Sail { // w1
TALL {protected int getHeight() {return 100;}},
SHORT {protected int getHeight() {return 2;}};
protected abstract int getHeight();
}
public Sail getSail() {
return Sail.TALL;
} }
public static void main(String[] stars) {
var bottle = new Bottle();
Ship q = bottle.new Ship(); // w2
System.out.print(q.getSail());
} }
TALL
w1
.w2
.static
initializer constructor, method declarationsp1
, causes the application to print 5
?
package games;
public class Jump {
private int rope = 1;
protected boolean outside;
public Jump() {
// line p1
outside = true;
}
public Jump(int rope) {
this.rope = outside ? rope : rope+1;
}
public static void main(String[] bounce) {
System.out.print(new Jump().rope);
} }
this(4);
new Jump(4);
this(5);
rope = 4;
super(4);
super(5);
public
.
Blanket
class can call the Flashlight
class's turnOn()
.Flashlight
class can call the Flashlight
class's replaceBulb()
.Phone
class can call the Blanket
class's wash()
.Tent
class can call the Tent
class's pitch()
.Tent
class can call the Blanket
class's wash()
.display()
method?
Tree
class immutable? (Choose three.)
1: public class Tree {
2: String species;
3: public Tree(String species) {
4: this.species = species;
5: }
6: public String getSpecies() {
7: return species;
8: }
9: private final void setSpecies(String newSpecies) {
10: species = newSpecies;
11: } }
private
.species
to private
.species
to protected
.setSpecies()
method.Tree
class final
.species
in the Tree
constructor.package ocean;
abstract interface CanSwim {
public void swim(final int distance);
}
public class Turtle {
final int distance = 2;
public static void main(String[] seaweed) {
final int distance = 3;
CanSwim seaTurtle = {
final int distance = 5;
@Override
public void swim(final int distance) {
System.out.print(distance);
}
};
seaTurtle.swim(7);
} }
2
3
5
7
package pet;
public class Puppy {
public static int wag = 5; // q1
public void Puppy(int wag) { // q2
this.wag = wag;
}
public static void main(String[] tail) {
System.out.print(new Puppy(2).wag); // q3
} }
2
5
q1
.q2
.q3
.void run(String government)
package desert;
interface CanBurrow {
public abstract void burrow();
}
@FunctionalInterface interface HasHardShell
extends CanBurrow {}
abstract class Tortoise implements HasHardShell {
public abstract int toughness();
}
public class DesertTortoise extends Tortoise {
public int toughness() { return 11; }
}
CanBurrow
HasHardShell
Tortoise
DesertTortoise
interface Building {
default Double getHeight() { return 1.0; } // m1
}
interface Office {
public default String getHeight() { return null; } // m2
}
abstract class Tower implements Building, Office {} // m3
public class Restaurant extends Tower {} // m4
m1
m2
m3
m4
public class Nature {
public static void main(String[] seeds) {
record Tree() {}
var tree = "pine";
int count = 0;
if (tree.equals("pine")) {
int height = 55;
count = count + 1;
}
System.out.print(height + count);
} }
1
55
56
/****** TODO */
# Fix this bug later
‘ Error closing pod bay doors
/ Invalid record /
/* Page not found */
// IGNORE ME
private
and final
abstract
and final
static
and private
private
and abstract
abstract
and static
static
and protected
package storage;
public class Box {
public String stuff;
_________________ String _________________() {
return stuff;
}
public void setStuff(String stuff) {
this.stuff = stuff;
} }
private
and getStuff
private
and isStuff
public
and getStuff
public
and isStuff
default
and getStuff
Interface member | Membership type | Requires method body? |
---|---|---|
static method | Class | Yes |
private non-static method | Class | Yes |
abstract method | Instance | No |
default method | Instance | No |
private static method | Class | Yes |
super
, this()
super
, super()
super()
, this
super()
, super
public sealed class Toy {
___________________________ extends Toy {}
}
nonsealed class Book
abstract class Robot
class ActionFigure
record Doll()
interface Game
non-sealed class Ball
Toy
does not include a permits
clauseWatch
program?
1: class SmartWatch extends Watch {
2: private String getType() { return "smart watch"; }
3: public String getName(String suffix) {
4: return getType() + suffix;
5: } }
6: public class Watch {
7: private String getType() { return "watch"; }
8: public String getName(String suffix) {
9: return getType() + suffix;
10: }
11: public static void main(String[] args) {
12: var watch = new Watch();
13: var smartWatch = new SmartWatch();
14: System.out.print(watch.getName(","));
15: System.out.print(smartWatch.getName(""));
16: } }
smart watch,watch
watch,smart watch
watch,watch
Movie
program?
package theater;
class Cinema {
private String name = "Sequel";
public Cinema(String name) {
this.name = name;
} }
public class Movie extends Cinema {
private String name = "adaptation";
public Movie(String movie) {
this.name = "Remake";
}
public static void main(String[] showing) {
System.out.print(new Movie("Trilogy").name);
} }
Sequel
Trilogy
Remake
Adaptation
null
import java.util.*;
public final class Ocean {
private final List<String> algae;
private final double wave;
private int sun;
public Ocean(double wave) {
this.wave = wave;
this.algae = new ArrayList<>();
}
public int getSun() {
return sun;
}
public void setSun(int sun) {
sun = sun;
}
public double getWave() {
return wave;
}
public List<String> getAlgae() {
return new ArrayList<String>(algae);
} }
Magnet.java
shown, which of the marked lines can you independently insert the line var color;
into and still have the code compile?
// line a1
public class Magnet {
// line a2
public void attach() {
// line a3
}
// line a4
}
a2
a3
a2
and a3
a1
, a2
, a3
, and a4
package sea;
enum Direction { north, south, east, west; };
public class Ship {
public static void main(String[] compass) {
System.out.print(Direction.valueOf(compass[0]));
} }
WEST
is printed.south
is printed.ArrayIndexOutOfBoundsException
is thrown at runtime.IllegalArgumentException
is thrown at runtime.package radio;
public class Song {
public void playMusic() {
System.out.print("Play!");
}
private static void playMusic() {
System.out.print("Music!");
}
private static void playMusic(String song) {
System.out.print(song);
}
public static void main(String[] tracks) {
new Song().playMusic();
} }
Play!
Music!
10: interface Flavor {
11: public default void happy() {
12: printFlavor("Rocky road");
13: }
14: private static void excited() {
15: printFlavor("Peanut butter");
16: }
17: private void printFlavor(String f) {
18: System.out.println("Favorite Flavor is: "+f);
19: }
20: public static void sad() {
21: printFlavor("Butter pecan");
22: }
23: }
24: public class IceCream implements Flavor {
25: @Override public void happy() {
26: printFlavor("Cherry chocolate chip");
27: } }
1: public record Disco(int beats) {
2: public Disco(String beats) {
3: this(20);
4: }
5: public Disco {
6: beats = 10;
7: }
8: public int getBeats() {
9: return beats;
10: }
11: public static void main(String[] args) {
12: System.out.print(new Disco(30).beats());
13: } }
10
20
30
const
final
abstract
static
public
constant
public static void main(String[] args) {
int Integer = 0; // k1
Integer int = 0; // k2
Integer ++; // k3
int++; // k4
int var = null; // k5
}
k1
k2
k3
k4
k5
public class Tolls {
private static int yesterday = 1;
int tomorrow = 10;
public static void main(String[] args) {
var tolls = new Tolls();
int today = 20, tomorrow = 40; // line x
System.out.print(
today + tolls.tomorrow + tolls.yesterday); // line y
} }
x
.y
.31
61
package weather;
public class Forecast {
public enum Snow {
BLIZZARD, SQUALL, FLURRY
@Override public String toString() { return "Sunny"; }
}
public static void main(String[] modelData) {
System.out.print(Snow.BLIZZARD.ordinal() + " ");
System.out.print(Snow.valueOf("flurry".toUpperCase()));
} }
0 FLURRY
1 FLURRY
0 Sunny
1 Sunny
super()
command.final
instance variable whose value is not set when it is declared or in an initialization block should be set by the constructor.play()
method can be called from all classes in the com.mammal
and com.mammal.eland
package, but not in the com.mammal.gopher
package?
package com.mammal;
public class Enrichment {
_______ void play() {}
}
private
protected
public
Rocket
program?
package transport;
class Ship {
protected int weight = 3;
protected int height = 5;
public int getWeight() { return weight; }
public int getHeight() { return height; }
}
public class Rocket extends Ship {
public int weight = 2;
public int height = 4;
public void printDetails() {
System.out.print(super.getWeight() + "," + this.height);
}
public static final void main(String[] fuel) {
new Rocket().printDetails();
} }
2,5
3,4
5,2
3,5
protected
.public
.static
.10
at runtime.
interface Speak {
public default int getVolume() { return 20; }
}
interface Whisper {
public default int getVolume() { return 10; }
}
public class Debate implements Speak, Whisper {
public int getVolume() { return 30; }
public static void main(String[] a) {
var d = new Debate();
System.out.println(_________________);
} }
Whisper.d.getVolume()
d.Whisper.getVolume()
Whisper.super.getVolume()
d.Whisper.super.getVolume()
abstract
?
public class Cars {
static {
System.out.println("static");
}
private static void drive() {
System.out.println("fast");
}
{ System.out.println("faster"); }
public static void main(String[] args) {
drive();
drive();
} }
public record Passenger(String firstName, String lastName) {
static String middleName;
@Override public String toString() {
return null;
}
@Override public String getFirstName() {
return null;
}
public static void main(String[] args) {
var p = new Passenger("John", "Colbert");
System.out.println(p.getFirstName());
} }
john
colbert
null
foo
is a reference to an instance of a class Foo
. Which of the following is not possible about the variable reference foo.bar
?
bar
is an instance variable.bar
is a static
variable.bar
is a local variable.bar
.bar
.Bunny
object in memory. The reference variable myBunny
is of type Bunny
, while unknownBunny
is a valid but unknown data type. Which statements about the reference variables are true? Assume the instance methods and variables shown in the diagram are marked public
. (Choose three.)
unknownBunny
must be Bunny
or a supertype of Bunny
.unknownBunny
cannot be cast to a reference type of Bunny
.unknownBunny
must be Bunny
or a subclass of Bunny
.unknownBunny
is Bunny
, it has access to all of the same methods and variables as myBunny
.unknownBunny
could be an interface, class, or abstract class.unknownBunny
is Object
, it has access to all of the same methods and variables as myBunny
without a cast.private
methodsprivate static
methodsdefault
methodsstatic
methodsabstract
methodsfinal
methodsinterface Lion {
public void roar();
default void drink() {}
String toString();
}
interface Tiger {
public void roar();
default void drink() {}
int hashCode();
}
Lion
Tiger
Lion
and Tiger
bounce
? (Choose two.)
public class TennisBall {
public TennisBall() {
System.out.println("bounce");
}
public static void main(String[] slam) {
_____________________________________;
} }
var new = TennisBall
TennisBall()
var var = new TennisBall()
new TennisBall
new TennisBall()
public
methods in the class compile?
public class Singing {
private void sing(String key) {}
public void sing_do(String key, String… harmonies) {
this.sing(key);
}
public void sing_re(int note, String… sound, String key) {
this.sing(key);
}
public void sing_me(String… keys, String… pitches) {
this.sing(key);
}
public void sing_fa(String key, String… harmonies) {
this.Singing.sing(key);
}
public void sing_so(int note, String… sound,
String key) {
this.Singing.sing(key);
}
public void sing_la(String… keys, String… pitches) {
this.Singing.sing(key);
} }
package world;
public class Matrix {
private int level = 1;
class Deep {
private int level = 2;
class Deeper {
private int level = 5;
public void printReality(int level) {
System.out.print(this.level+" ");
System.out.print(Matrix.Deep.this.level+" ");
System.out.print(Deep.this.level);
} } }
public static void main(String[] bots) {
Matrix.Deep.Deeper simulation = new Matrix()
.new Deep().new Deeper();
simulation.printReality(6);
} }
1 1 2
5 2 2
5 2 1
6 2 2
6 2 1
Time
declaration, how many declarations compile? Assume they are all declared within the same .java
file.
public sealed interface Time permits Hour, Minute, Second {}
record Hour() implements Time {}
interface Minute extends Time {}
non-sealed class Second implements Time {}
class Micro extends Second {}
Integer
and Long
are direct subclasses of Number
, what type can be used to fill in the blank in the following class to allow it to compile?
package orchestra;
interface MusicCreator { public Number play(); }
abstract class StringInstrument {
public Long play() {return 3L;}
}
public class Violin extends StringInstrument
implements MusicCreator {
public _________________ play() {
return null;
} }
Long
Integer
Long
or Integer
Long
or Number
Long
, Integer
, or Number
RightTriangle
program?
package shapes;
abstract class Triangle {
abstract String getDescription();
}
abstract class IsoRightTriangle extends RightTriangle { // g1
public String getDescription() { return "irt"; }
}
public class RightTriangle extends Triangle {
protected String getDescription() { return "rt"; } // g2
public static void main(String[] edges) {
final var shape = new IsoRightTriangle(); // g3
System.out.print(shape.getDescription());
} }
rt
irt
g1
.g2
.g3
.interface Dog {
private void buryBone() { chaseTail(); }
private static void wagTail() { chaseTail(); }
public default String chaseTail() { return "So cute!"; }
}
public class Puppy implements Dog {
public String chaseTail() throws IllegalArgumentException {
throw new IllegalArgumentException("Too little!");
}
public static void main(String[] t) {
var p = new Puppy();
System.out.print(p.chaseTail());
} }
So cute!
Too little!
message.buryBone()
is not used.chaseTail()
cannot declare any exceptions in the Puppy
class.System.forceGc()
System.gc()
System.requireGc()
GarbageCollection.clean()
package shield;
public class Protect {
private String material;
protected int strength;
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
} }
material
.material
.material
to protected
.strength
to private
.static
variables can be used regardless of whether they are effectively final.static
variables can be used regardless of whether they are effectively final.static
variables can be used regardless of whether they are effectively final.import java.util.*;
final class Faucet {
private final String water;
private final List<Double> pipes;
public Faucet(String water, List<Double> pipes) {
this.water = water;
this.pipes = pipes;
}
public String getWater() { return water; }
public List<Double> getPipes() { return pipes; } }
public final class Spout {
private final String well;
private final List<Boolean> buckets;
public Spout(String well, List<Boolean> buckets) {
this.well = well;
this.buckets = new ArrayList<>(buckets);
}
public String getWell() { return well; }
public List<Boolean> getBuckets() {
return new ArrayList<>(buckets);
} }
Faucet
is immutable.Spout
is immutable.true
? (Choose three.)
interface Friendly {}
abstract class Dolphin implements Friendly {}
class Animal implements Friendly {}
class Whale extends Object {}
class Fish {}
class Coral extends Animal {}
new Coral() instanceof Friendly
null instanceof Object
new Coral() instanceof Object
new Fish() instanceof Friendly
new Whale() instanceof Object
new Dolphin() instanceof Friendly
public class Eggs {
enum Animal {
CHICKEN(21), PENGUIN(75);
private int numDays;
private Animal(int numDays) {
this.numDays = numDays;
}
public int getNumDays() {
return numDays;
}
public void setNumDays(int numDays) {
this.numDays = numDays;
} }
public static void main(String[] args) {
Animal chicken = Animal.CHICKEN;
chicken.setNumDays(20);
System.out.print(chicken.getNumDays());
System.out.print(" ");
System.out.print(Animal.CHICKEN.getNumDays());
System.out.print(" ");
System.out.print(Animal.PENGUIN.getNumDays());
} }
20 20 20
.20 20 75
.20 21 75
.21 21 75
.setNumDays()
.1: public interface Thunderstorm {
2: float rain = 1;
3: char getSeason() { return 'W'; }
4: boolean isWet();
5: private static void hail() {}
6: default String location() { return "Home"; }
7: private static int getTemp() { return 35; }
8: }
package finance;
enum Currency { DOLLAR, YEN, EURO }
abstract class Provider {
protected Currency c = Currency.EURO;
}
public class Bank extends Provider {
protected Currency c = Currency.DOLLAR;
public static void main(String[] pennies) {
int value = 0;
switch(new Bank().c) {
case 0:
value--; break;
case 1:
value++; break;
}
System.out.print(value);
} }
-1
0
1
Provider
class does not compile.Bank
class does not compile.hashCode()
static
initializersstatic
methodsvar q = 4.0f;
?
float q = 4.0f;
Float q = 4.0f;
double q = 4.0f;
Double q = 4.0f;
Object q = 4.0f;
static
classstatic
methods.default
methods.private static
methods.abstract
methods.private
methods.X
can be replaced by arbitrary code?
// Mandrill.java
public class Mandrill {
public int age;
public Mandrill(int age) {
this.age = age;
}
public String toString() {
return "" + age;
}
}
// PrintAge.java
public class PrintAge {
public static void main (String[] args) {
var mandrill = new Mandrill(5);
// line X
System.out.println(mandrill);
} }
0
5
0
or 5
int
valueString
objects are eligible for garbage collection right before the end of the main()
method?
public static void main(String[] ohMy) {
String animal1 = new String("lion");
String animal2 = new String("tiger");
String animal3 = new String("bear");
animal3 = animal1;
animal2 = animal3;
animal1 = animal2;
}
Panther
and Cub
are interfaces and neither contains any default
methods. Which statements are true? (Choose two.)
Panther
has a single abstract
method, Cub
is guaranteed to be a functional interface.Panther
has a single abstract
method, Cub
may be a functional interface.Panther
has a single abstract
method, Cub
cannot be a functional interface.Panther
has two abstract
methods, Cub
is guaranteed to be a functional interface.Panther
has two abstract
methods, Cub
may be a functional interface.Panther
has two abstract
methods, Cub
cannot be a functional interface.1: public class InitOrder {
2: public String first = "instance";
3: public InitOrder() {
4: first = "constructor";
5: }
6: { first = "block"; }
7: public void print() {
8: System.out.println(first);
9: }
10: public static void main(String… args) {
11: new InitOrder().print();
12: } }
block
constructor
instance
public interface Tree {
public static void produceSap() {
growLeaves();
}
public abstract int getNumberOfRings() {
return getNumberOfRings();
}
private static void growLeaves() {
produceSap();
}
public default int getHeight() {
return getHeight ();
} }
produceSap()
does not compile.getNumberOfRings()
does not compile.growLeaves()
does not compile.getHeight()
does not compile.var
are true? (Choose two.)
null
at initialization without any type information.null
after initialization.null
.Bouncer
with a protected
variable. Methods in which class can access this variable?
Bouncer
or any class in the same package as Bouncer
Bouncer
Bouncer
Bouncer
package forest;
public class Woods {
static class Tree {}
public static void main(String[] leaves) {
int heat = 2;
int water = 10-heat;
final class Oak extends Tree { // p1
public int getWater() {
return water; // p2
}
}
System.out.print(new Oak().getWater());
water = 0;
} }
8
p1
contains a compiler error.p2
contains a compiler error.interface Australian {}
interface Mammal {}
___________________ Australian, Mammal {}
class Quokka extends
class Quokka implements
interface Quokka extends
interface Quokka implements
public void setColor(String color) {
color = color;
}
this()
in a constructor are true? (Choose three.)
this()
, then there must be a constructor in the class that can take those arguments.this()
, then there must be a constructor in the superclass that can take those arguments.this()
is called within a constructor, then the class must explicitly implement the no-argument constructor.super()
and this()
are both used in the same constructor, super()
must appear on the line immediately after this()
.super()
and this()
are both used in the same constructor, this()
must appear on the line immediately after super()
.this()
is used, it must be the first line of the constructor.public class RollerSkates {
static int wheels = 1;
int tracks = 5;
public static void main(String[] wheels) {
RollerSkates s = new RollerSkates();
int feet = 4, tracks = 15;
System.out.print(feet + tracks + s.wheels);
} }
4
5
10
20
package vessel;
class Problem extends Exception {}
abstract class Danger {
protected abstract void isDanger() throws Problem; // m1
}
public class SeriousDanger extends Danger { // m2
protected void isDanger() throws Exception { // m3
throw new RuntimeException(); // m4
}
public static void main(String[] w) throws Throwable { // m5
var sd = new SeriousDanger().isDanger(); // m6
} }
m1
.m2
.m3
.m4
.m5
.m6
.protected
.final
.private
.private
variables of the top-level class in which it is defined.abstract
.class
declarationpackage
statementimport
statementclass
declaration and package
statementclass
declaration and at least one import
statementpublic
modifiermain()
method?
1: public class Person {
2: public Person youngestChild;
3:
4: public static void main(String… args) {
5: Person elena = new Person();
6: Person janeice = new Person();
7: elena.youngestChild = janeice;
8: janeice = null;
9: Person zoe = new Person();
10: elena.youngestChild = zoe;
11: zoe = null;
12: } }
package race;
interface Drive {
int SPEED = 5;
default Integer getSpeed() { return SPEED; }
}
interface Hover {
String MAX_SPEED = "10";
default String getSpeed() { return MAX_SPEED; }
}
public class Car implements Drive, Hover {
@Override public Object getSpeed() { return 15; }
public static void main(String[] gears) {
System.out.print(new Car().getSpeed());
} }
5
10
15
1: public class ChooseWisely {
2: public ChooseWisely() { super(); }
3: public int choose(int choice) { return 5; }
4: public int choose(short choice) { return 2; }
5: public int choose(long choice) { return 11; }
6: public int choose(double choice) { return 6; }
7: public int choose(Float choice) { return 8; }
8: public static void main(String[] path) {
9: ChooseWisely c = new ChooseWisely();
10: System.out.println(c.choose(2f));
11: System.out.println(c.choose((byte)2+1));
12: } }
2
3
5
6
8
11
1: public enum Color {
2: RED(1,2) { void toSpectrum() {} },
3: BLUE(2) { void toSpectrum() {} void printColor() {} },
4: ORANGE() { void toSpectrum() {} },
5: GREEN(4);
6: public Color(int… color) {}
7: abstract void toSpectrum();
8: final void printColor() {}
9: }
Square
program?
package shapes;
abstract class Trapezoid {
private int getEqualSides() {return 0;}
}
abstract class Rectangle extends Trapezoid {
public static int getEqualSides() {return 2;} // x1
}
public class Square extends Rectangle {
public int getEqualSides() {return 4;} // x2
public static void main(String[] corners) {
final Square myFigure = new Square() {}; // x3
System.out.print(myFigure.getEqualSides());
} }
0
2
4
x1
.x2
.x3
.play()
method can be called from all classes in the com.mammal
package but not the com.mammal.gopher
package?
package com.mammal;
public class Enrichment {
___________ void play() {}
}
private
protected
public
Type | Allows abstract methods? | Allows constants? | Allows constructors? |
---|---|---|---|
Abstract class | Yes | Yes | No |
Concrete class | Yes | Yes | Yes |
Interface | Yes | Yes | Yes |
void
default
public
private
volatile
final
nonsealed
abstract
methods.abstract
method.private
methods.private
method.static
methods.static
method.package wrap;
public class Gift {
private final Object contents;
protected Object getContents() {
return contents;
}
protected void setContents(Object contents) {
this.contents = contents;
}
public void showPresent() {
System.out.print("Your gift: "+contents);
}
public static void main(String[] treats) {
var gift = new Gift();
gift.setContents(gift);
gift.showPresent();
} }
Your gift: wrap.Gift@29ca2745
Your gift: Your gift:
1: package animal;
2: interface CanFly {
3: public void fly() {}
4: int speed = 5;
5: }
6: final class Bird {
7: public int fly(int speed) {}
8: }
9: public class Eagle extends Bird implements CanFly {
10: public void fly() {}
11: }
public class Bunny {
static class Rabbit {
void hop() {
System.out.print("hop");
}
}
static class FlemishRabbit extends Rabbit {
void hop() {
System.out.print("HOP");
}
}
public static void main(String[] args) {
Rabbit r1 = new FlemishRabbit();
FlemishRabbit r2 = new FlemishRabbit();
r1.hop();
r2.hop();
} }
hophop
HOPhop
hopHOP
HOPHOP
class _ {}
class river {}
class Str3@m {}
class Pond2$ {}
class _var_ {}
class 5Ocean {}
InfiniteMath
program?
class Math {
public final double secret = 2;
}
class ComplexMath extends Math {
public final double secret = 4;
}
public class InfiniteMath extends ComplexMath {
public final double secret = 8;
public static void main(String[] numbers) {
Math math = new InfiniteMath();
System.out.print(math.secret);
} }
2.0
4.0
8.0
mySkier
, mySpeed
, and myName
variables in the main()
method after the call to the slalom()
method?
package slopes;
public class Ski {
private int age = 18;
private static void slalom(Ski racer,
int[] speed, String name) {
racer.age = 18;
name = "Wendy";
speed = new int[1];
speed[0] = 11;
racer = null;
}
public static void main(String[] mountain) {
final var mySkier = new Ski();
mySkier.age = 16;
final int[] mySpeed = new int[1];
final String myName = "Rosie";
slalom(mySkier, mySpeed, myName);
} }
package zoo;
public class Penguin {
private int volume = 1;
private class Chick {
private static int volume = 3;
void chick(int volume) {
System.out.print("Honk("+Penguin.this.volume+")!");
} }
public static void main(String… eggs) {
Penguin pen = new Penguin();
final Penguin.Chick littleOne = pen.new Chick();
littleOne.chick(5);
} }
Honk(1)!
Honk(3)!
Honk(5)!
record Name(String v) {}
public record Fruit(Name n) {
public static void main(String[] vitamins) {
var x = new Name("Apple");
System.out.println(new Fruit(x));
} }
Fruit@3f2f5b24
Fruit[Apple]
Fruit[Name[Apple]]
Fruit[n=Apple]
Fruit[n=Name[v=Apple]]
Fruit[v=Apple]
X
at runtime.
interface Fruit {
public default char getColor() { return 'Z'; }
}
interface Edible {
public default char getColor() { return 'X'; }
}
public class Banana implements Fruit, Edible {
public char getColor() { return _________________; }
public static void main(String[] a) {
var d = new Banana();
System.out.println(d.getColor());
} }
Edible.getColor()
Edible.super.getColor()
super.Edible.getColor()
super.getColor()
package clothes;
public class Store {
public static String getClothes() { return "dress"; }
}
package wardrobe;
// INSERT CODE HERE
public class Closet {
public void borrow() {
System.out.print("Borrowing clothes: "+getClothes());
} }
static import clothes.Store.getClothes;
import clothes.Store.*;
import static clothes.Store.getClothes;
import static clothes.Store;
ElectricCar
program?
package vehicles;
class Automobile {
private final String drive() { return "Driving vehicle"; }
}
class Car extends Automobile {
protected String drive() { return "Driving car"; }
}
public class ElectricCar extends Car {
public final String drive() { return "Driving electric car"; }
public static void main(String[] wheels) {
final Automobile car = new ElectricCar();
var v = (Car)car;
System.out.print(v.drive());
} }
Driving vehicle
Driving electric car
Driving car
ClassCastException
at runtime.abstract
.final
.public class Music {
{ System.out.print("do-"); }
static { System.out.print("re-"); }
{ System.out.print("mi-"); }
static { System.out.print("fa-"); }
public Music() {
System.out.print("so-");
}
public Music(int note) {
System.out.print("la-");
}
public static void main(String[] sound) {
System.out.print("ti-");
var play = new Music();
} }
re-fa-ti-do-mi-so-
do-re-mi-fa-ti-so-
ti-re-fa-do-mi-so-
re-fa-la-mi-ti-do-
do-re-mi-fa-so-ti
public class Earth {
private abstract class Sky {
void fall() {
var e = _________________
} } }
new Sunset() extends Sky {};
new Sky();
new Sky() {}
new Sky() { final static int blue = 1; };
Encyclopedia
program?
package paper;
abstract class Book {
protected static String material = "papyrus";
public Book() {}
abstract String read() {}
public Book(String material) {this.material = material;}
}
public class Encyclopedia extends Book {
public static String material = "cellulose";
public Encyclopedia() {super();}
public String read() { return "Reading is fun!"; }
public String getMaterial() {return super.material;}
public static void main(String[] pages) {
System.out.print(new Encyclopedia().read());
System.out.print("-" + new Encyclopedia().getMaterial());
} }
Reading is fun!-papyrus
Reading is fun!-cellulose
null-papyrus
null-cellulose
interface Vehicle {}
class Bus implements Vehicle {}
public class Transport {
public static void main(String[] args) {
Vehicle vehicle = new Bus();
boolean n = null instanceof Bus;
boolean v = vehicle instanceof Vehicle;
boolean b = vehicle instanceof Bus;
System.out.println(n + " " + v + " " + b);
} }
false false false
false false true
false true true
true false true
true true false
true true true
Interface member | Optional modifier(s) | Required modifier(s) |
---|---|---|
Private method | private | - |
Default method | public | default |
Static method | public static | - |
Abstract method | public | abstract |
public class Dwarf {
private final String name;
public Dwarf() {
this("Bashful");
}
public Dwarf(String name) {
name = "Sleepy";
}
public static void main(String[] sound) {
var d = new Dwarf("Doc");
System.out.println(d.name);
} }
Sleepy
Bashful
Doc
package pocketmath;
interface AddNumbers {
int add(int x, int y);
static int subtract(int x, int y) { return x-y; }
default int multiply(int x, int y) { return x*y; }
}
public class Calculator {
protected void calculate(AddNumbers n, int a, int b) {
System.out.print(n.add(a, b));
}
public static void main(String[] moreNumbers) {
final var ti = new Calculator() {};
ti.calculate((k,p) -> p+k+1, 2, 5); // x1
} }
0
7
8
AddNumbers
is not a functional interface.x1
.construct()
parent()
super()
this()
that()
overthere()
Grasshopper
program?
// Hopper.java
package com.animals;
public class Hopper {
protected void hop() {
System.out.println("hop");
}
}
// Grasshopper.java
package com.insect;
import com.animals.Hopper;
public class Grasshopper extends Hopper {
public void move() {
hop(); // p1
}
public static void main(String[] args) {
var hopper = new Grasshopper();
hopper.move(); // p2
hopper.hop(); // p3
} }
hop
once.hop
twice.p1
.p2
.p3
.@FunctionalInterface
public interface Play {
public static void baseball() {}
private static void soccer() {}
default void play() {}
void fun();
void game();
void toy();
}
import java.util.*;
public class Flower {
private final String name;
private final List<Integer> counts;
public Flower(String name, List<Integer> counts) {
this.name = name;
this.counts = new ArrayList<>(counts);
}
public final String getName() { return name; }
public final List<Integer> getCounts() {
return new ArrayList<>(counts);
} }
class Plant {
private final String name;
private final List<Integer> counts;
public Plant(String name, List<Integer> counts) {
this.name = name;
this.counts = new ArrayList<>(counts);
}
public String getName() { return name; }
public List<Integer> getCounts() {
return new ArrayList<>(counts);
} }
Flower
is immutable.Plant
is immutable.Sounds
program?
// Sheep.java
package com.mammal;
public class Sheep {
private void baa() {
System.out.println("baa!");
}
private void speak() {
baa();
} }
// Sounds.java
package com.animals;
import com.mammal.Sheep;
public class Sounds {
public static void main(String[] args) {
var sheep = new Sheep();
sheep.speak();
} }
baa!
.Sheep
class does not compile.Sounds
class does not compile.package stocks;
public class Bond {
private static int price = 5;
public boolean sell() {
if(price<10) {
price++;
return true;
} else if(price>=10) {
return false;
} }
public static void main(String[] cash) {
new Bond().sell();
new Bond().sell();
new Bond().sell();
System.out.print(price);
} }
5
6
7
8
88
is printed at runtime?
final public class Racecar {
final private int speed = 88;
final protected class Engine {
private final int speed = 100;
public final int getSpeed() {
return ________________________;
}
}
final Engine e = new Engine();
final public static void main(String[] feed) {
System.out.print(new Racecar().e.getSpeed());
} }
Racecar.speed
this.speed
this.Racecar.speed
Racecar.Engine.this.speed
Racecar.this.speed
static
initializers are correct? (Choose three.)
static final
variable.new
keyword.BlueCar
program?
package race;
abstract class Car {
static { System.out.print("1"); }
public Car(String name) {
super();
System.out.print("2");
}
{ System.out.print("3"); } }
public class BlueCar extends Car {
{ System.out.print("4"); }
public BlueCar() {
super("blue");
System.out.print("5");
}
public static void main(String[] gears) {
new BlueCar();
} }
23451
12345
14523
13245
23154
Fish
class is included, unmodified, in a larger program at runtime. As most, how many classes can inherit Fish
(excluding Fish
itself)?
public sealed class Fish {
final class Blobfish extends Clownfish {}
private non-sealed class Dory extends BlueTang {}
sealed class Clownfish extends Fish {}
sealed class BlueTang extends Fish {}
final class Swordfish extends Fish {}
private non-sealed class Nemo extends Clownfish {}
}
package mammal;
interface Pet {
public Object getDoggy();
}
public class Canine implements Pet {
public __________ getDoggy() {
return this;
} }
Canine
List
Object
Pet
public interface Movie {
String pass = "TICKET";
private void buyPopcorn() {
purchaseTicket();
}
public static int getDrink() {
buyPopcorn();
return 32;
}
private static String purchaseTicket() {
getDrink();
return pass;
} }
buyPopcorn()
does not compile.getDrink()
does not compile.purchaseTicket()
does not compile.class YardWork {
private static int numShovels;
private int numRakes;
public int getNumShovels() {
return numShovels;
}
public int getNumRakes() {
return numRakes;
} }
getNumRakes()
getNumShovels()
1: class Fly {
2: public Fly Fly() { return new Fly(); }
3: public void Fly(int kite) {}
4: public int Fly(long kite) { return 1; }
5: public static void main(String[] a) {
6: var f = new Fly();
7: f.Fly();
8: } }
sky()
method?
light
variable?
public static
interface method? (Choose two.)
static
methods to access instance methods.HighSchool
application?
package edu;
import java.io.FileNotFoundException;
abstract class School {
abstract Float getNumTeachers();
public int getNumStudents() {
return 10;
} }
public class HighSchool extends School {
final Float getNumTeachers() { return 4f; }
public int getNumStudents() throws FileNotFoundException {
return 20;
}
public static void main(String[] s) throws Exception {
var school = new HighSchool();
System.out.print(school.getNumStudents());
} }
10
20
4.0
package track;
interface Run {
default CharSequence walk() {
return "Walking and running!";
} }
interface Jog {
default String walk() {
return "Walking and jogging!";
} }
public class Sprint implements Run, Jog {
public String walk() {
return "Sprinting!";
}
public static void main(String[] args) {
var s = new Sprint();
System.out.println(s.walk());
} }
Walking and running!
Walking and jogging!
Sprinting!
interface Crawl {
abstract void wriggle();
}
interface Dance {
public void wriggle();
}
wriggle()
.wriggle()
.public
modifier were removed but must implement wriggle()
.public
modifier were removed, a concrete class could implement both interfaces, but must not implement wriggle()
.interface Lion {
public void roar();
default void drink() {}
boolean equals(Lion lion);
}
interface Tiger {
public void roar();
default void drink() {}
String toString(String name);
}
interface Bear {
void ohMy();
default void drink() {}
}
Lion
Tiger
Bear
Lion
and Tiger
Tiger
and Bear
Bear
and Lion
1: public class Dragon {
2: boolean scaly;
3: static final int gold;
4: Dragon protectTreasure(int value, boolean scaly) {
5: scaly = true;
6: return this;
7: }
8: static void fly(boolean scaly) {
9: scaly = true;
10: }
11: int saveTheTreasure(boolean scaly) {
12: return this.gold;
13: }
14: static void saveTheDay(boolean scaly) {
15: this.gold = 0;
16: }
17: static { gold = 100; } }
private
constructor is provided.private
.final
.public interface Planet {
int circumference;
public abstract void enterAtmosphere();
public default int getCircumference() {
enterAtmosphere();
return circumference;
}
private static void leaveOrbit() {
var earth = new Planet() {
public void enterAtmosphere() {}
};
earth.getCircumference();
} }
enterAtmosphere()
does not compile.getCircumference()
does not compile.leaveOrbit()
does not compile.import java.time.*;
import java.time.temporal.*;
public record User(LocalDate creationDate) {
static LocalDate today = LocalDate.now();
public User {
creationDate = today;
creationDate = today;
}
public static void main(String[] p) {
LocalDate yesterday = LocalDate.now()
.minus(1, ChronoUnit.DAYS);
var u = new User(yesterday);
System.out.print(u.creationDate());
} }
null
public class Husky {
{ this.food = 10; }
{ this.toy = 2; }
private final int toy;
private static int food;
public Husky(int friend) {
this.food += friend++;
this.toy -= friend--;
}
public static void main(String… unused) {
var h = new Husky(2);
System.out.println(h.food+","+h.toy);
} }
12,-1
12,2
13,-1
main()
method, assuming garbage collection hasn't run?
1: public class Link {
2: private String name;
3: private Link next;
4: public Link(String name, Link next) {
5: this.name = name;
6: this.next = next;
7: }
8: public void setNext(Link next) {
9: this.next = next;
10: }
11: public Link getNext() {
12: return next;
13: }
14: public static void main(String… args) {
15: var apple = new Link("x", null);
16: var orange = new Link("y", apple);
17: var banana = new Link("z", orange);
18: orange.setNext(banana);
19: banana.setNext(orange);
20: apple = null;
21: banana = null;
22: } }
super()
in one of its constructors, its parent class must explicitly implement a constructor.public class Complex {
class Building {}
final class House extends Building {}
public void convert() {
Building b1 = new Building();
House h1 = new House();
Building b2 = new House();
Building b3 = (House) b1;
House h2 = (Building) h1;
Building b4 = (Building) b2;
House h3 = (House) b2;
} }
b2
b3
h2
b4
h3
1: interface Tasty {
2: default void eat() {
3: System.out.print("Spoiled!");
4: } }
5: public class ApplePicking {
6: public static void main(String[] food) {
7: var apple = new Tasty() {
8: @Override
9: void eat() {
10: System.out.print("Yummy!");
11: }
12: }
13: }
14: }
Spoiled!
Yummy!
float
, char
, or short
.Tortoise
program?
// Hare.java
package com.mammal;
public class Hare {
void init() {
System.out.print("init-");
}
protected void race() {
System.out.print("hare-");
} }
// Tortoise.java
package com.reptile;
import com.mammal.Hare;
public class Tortoise {
protected void race(Hare hare) {
hare.init(); // x1
hare.race(); // x2
System.out.print("tortoise-");
}
public static void main(String[] args) {
var tortoise = new Tortoise();
var hare = new Hare();
tortoise.race(hare);
} }
init-hare-tortoise
init-hare
line x1
.line x2
.interface Tool {
void use(int fun);
}
abstract class Childcare {
abstract void use(int fun);
}
final public class Stroller extends Childcare implements Tool {
final public void use(int fun) {
final int width = 5;
class ParkVisit {
final int getValue() { return width + fun; }
}
System.out.print(new ParkVisit().getValue());
} }
Bush
program?
// Evergreen.java
package tree;
public class Evergreen {
String leaves = "Green ";
default void season() {
System.out.println("spring");
}
default void bloom() {
season();
} }
// Bush.java
package shrub;
import tree.Evergreen;
public class Bush {
public static void main(String[] args) {
var var = new Evergreen();
System.out.print(var.leaves);
var.bloom();
} }
Green spring
.Green springspring
.Evergreen
class does not compile.Bush
class does not compile.public sealed class Seasons {
final static class Spring extends Seasons {}
non-sealed class Summer extends Seasons {}
public static void main(String[] w) {
var t = new Spring();
final String m = switch (t) {
case Spring -> "Flowers";
case Summer -> "Pool";
default -> "Snow";
};
System.out.print(m);
} }
Flowers
Pool
Snow
Spring
declaration does not compile.Summer
declaration does not compile.main()
method does not compile.static
method private
within an interface?
abstract
.static
methods are implicitly private
within an interface.package jungle;
public class RainForest extends Forest {
public RainForest(long treeCount) {
this.treeCount = treeCount+1;
}
public static void main(String[] birds) {
System.out.print(new RainForest(5).treeCount);
} }
class Forest {
public long treeCount;
public Forest(long treeCount) {
this.treeCount = treeCount+2;
} }
5
6
7
8
package sports;
public class Bicycle {
String color = "red";
private void printColor(String color) {
color = "purple";
System.out.print(color);
}
public static void main(String[] rider) {
new Bicycle().printColor("blue");
} }
red
purple
blue
null
Short
and Integer
extend Number
directly, what type can be used to fill in the blank in the following class to allow it to compile?
package band;
interface Horn {
public Integer play();
}
abstract class Woodwind {
public Short play() {
return 3;
} }
public final class Saxophone extends Woodwind implements Horn {
public _________________ play() {
return null;
} }
Object
Integer
Short
Number
final
class.final
method.public enum Proposition {
TRUE(1) { String getNickName() { return "RIGHT"; }},
FALSE(2) { public String getNickName() { return "WRONG"; }},
UNKNOWN(3) { public String getNickName() { return "LOST"; }}
public int value;
Proposition(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
protected abstract String getNickName();
}
HopCounter
program?
// Hopper.java
package com.animals;
public class Hopper {
protected void hop() {
System.out.println("hop");
} }
// Grasshopper.java
package com.insect;
import com.animals.Hopper;
public class Grasshopper extends Hopper {
public void move() {
hop(); // p1
} }
// HopCounter.java
package com.insect;
public class HopCounter {
public static void main(String[] args) {
var hopper = new Grasshopper();
hopper.move(); // p2
hopper.hop(); // p3
} }
hop
once.hop
twice.p1
.p2
.p3
.abstract
methods.default
methods.protected
methods.public
methods.static
variables.findAverage()
method? (Choose two.)
public class Calculations {
public Integer findAverage(int sum) { return sum; }
}
public Long findAverage(int x)
public Long findAverage(int x, int y)
public Integer average(int x)
private void findAverage(int x)
public Integer findAverage(int… x) throws Exception
private Integer findAverage(int x)
Go_$Outside$2()
have-Fun()
new()
9enjoyTheWeather()
$sprint()
walk#()
abstract
method, the @Override
annotationstatic
methodsabstract
method, the @FunctionalInterface
annotationstatic
method, at most one default
method15
at runtime.
package love;
interface Sport {
private int play() { return 15; }
}
interface Tennis extends Sport {
private int play() { return 30; }
}
public class Game implements Tennis {
public int play() { return _________________; }
public static void main(String… ace) {
System.out.println(new Game().play());
} }
Sport.play()
Sport.super.play()
Sport.Tennis.play()
Tennis.Sport.super.play()
public class MoreMusic {
{
System.out.print("do-");
System.out.print("re-");
}
public MoreMusic() {
System.out.print("mi-");
}
public MoreMusic(int note) {
this(null);
System.out.print("fa-");
}
public MoreMusic(String song) {
this(9);
System.out.print("so-");
}
public static void main(String[] sound) {
System.out.print("la-");
var play = new MoreMusic(1);
} }
la-do-re-mi-so-fa-
la-do-re-mi-fa-
do-re-mi-fa-so-la-
fa-re-do-mi-so-
Hug
program?
public class Kitten {
/** private **/ float cuteness;
/* public */ String name;
// default double age;
void meow() { System.out.println(name + " - "+cuteness); }
}
public class Hug {
public static void main(String… friends) {
var k = new Kitten();
k.cuteness = 5;
k.name = "kitty";
k.meow();
} }
kitty - 5.0
Kitten
class does not compile.Hug
class does not compile.Kitten
and Hug
classes do not compile.package prepare;
interface Ready {
static int first = 2;
final short DEFAULT_VALUE = 10;
GetSet go = new GetSet(); // n1
}
public class GetSet implements Ready {
int first = 5;
static int second = DEFAULT_VALUE; // n2
public static void main(String[] begin) {
var r = new Ready() {};
System.out.print(r.first); // n3
System.out.print(" " + second); // n4
} }
2 10
5 10
5 2
n1
.n2
.n3
.n4
.Tortoise
program?
// Hare.java
package com.mammal;
public class Hare {
public void init() {
System.out.print("init-");
}
protected void race() {
System.out.print("hare-");
} }
// Tortoise.java
package com.reptile;
import com.mammal.Hare;
public class Tortoise extends Hare {
protected void race(Hare hare) {
hare.init(); // x1
hare.race(); // x2
System.out.print("tortoise-");
}
public static void main(String[] args) {
var tortoise = new Tortoise();
var hare = new Hare();
tortoise.race(hare);
} }
init-hare-tortoise
init-hare
x1
.x2
.interface Autobot {}
public record Transformer(Boolean matrix) implements Autobot {
public boolean isMatrix() {
return matrix;
}
abstract void transform() {}
public Transformer {
if(matrix == null)
throw new IllegalArgumentException();
}
public static void main(String[] u) {
var prime = new Transformer(null) {
public void transform() {}
};
System.out.print(prime.matrix());
} }
true
false
Movie
program?
// Story.java
package literature;
public abstract class Story {
private void tell() {
System.out.println("Once upon a time");
}
public static void play() {
tell();
} }
// Movie.java
package media;
import literature.Story;
public class Movie {
public static void main(String[] args) {
var story = new Story();
story.play();
} }
Once upon a time
.Story
class does not compile.Movie
class does not compile.Helicopter
program?
package flying;
class Rotorcraft {
protected final int height = 5;
abstract int fly();
}
interface CanFly {}
public class Helicopter extends Rotorcraft implements CanFly {
private int height = 10;
protected int fly() {
return super.height;
}
public static void main(String[] unused) {
Helicopter h = (Helicopter)new Rotorcraft();
System.out.print(h.fly());
} }
5
10
ClassCastException
at runtime.1: public class Electricity {
2: interface Power {}
3: public static void main(String[] light) {
4: class Source implements Power {};
5: final class Super extends Source {};
6: var start = new Super() {};
7: var end = new Source() { static boolean t = true; };
8: } }
package prepare;
public class Ready {
protected static int first = 2;
private static final short DEFAULT_VALUE = 10;
private static class GetSet {
int first = 5;
static int second = DEFAULT_VALUE;
}
private GetSet go = new GetSet();
public static void main(String[] begin) {
Ready r = new Ready();
System.out.print(r.go.first);
System.out.print(", "+r.go.second);
} }
2, 5
5, 10
5, 5
2, 10
GetSet
class declaration.public class Values {
static _________ defaultValue = 8;
static _________ DEFAULT_VALUE;
public static void main(String[] args) {
System.out.println("" + defaultValue + DEFAULT_VALUE);
} }
double
, it prints 8.00.0
.double
, it prints 8.0
.int
, it prints 8
.int
, it prints 80
.var
, it prints 8
.var
, it prints 80
.Gems
objects are eligible for garbage collection right before the end of the main()
method?
public record Gems(String name) {
public static void main(String… args) {
var g1 = Gems("Garnet");
var g2 = Gems("Amethyst");
var g3 = Gems("Pearl");
var g4 = Gems("Steven");
g2 = g3;
g3 = g2;
g1 = g2;
g4 = null;
} }
package sky;
public class Stars {
private int inThe = 4;
public void Stars() {
super();
}
public Stars(int inThe) {
this.inThe = this.inThe;
}
public static void main(String[] endless) {
System.out.print(new sky.Stars(2).inThe);
} }
package sports;
abstract class Ball {
protected final int size;
public Ball(int size) {
this.size = size;
} }
interface Equipment {}
public class SoccerBall extends Ball implements Equipment {
public SoccerBall() {
super(5);
}
public Ball get() { return this; }
public static void main(String[] passes) {
var equipment = (Equipment)(Ball)new SoccerBall().get();
System.out.print(((SoccerBall)equipment).size);
} }
5
55
ClassCastException
at runtime.Elephant
program is correct?
package stampede;
interface Long {
Number length();
}
public class Elephant {
public class Trunk implements Long {
public Number length() { return 6; } // k1
}
public class MyTrunk extends Trunk { // k2
public Integer length() { return 9; } // k3
}
public static void charge() {
System.out.print(new MyTrunk().length());
}
public static void main(String[] cute) {
new Elephant().charge(); // k4
} }
9
.k1
.k2
.k3
.k4
.1: package figures;
2: public class Dolls {
3: public int num() { return 3.0; }
4: public int size() { return 5L; }
5:
6: public void nested() { nested(2,true); }
7: public int nested(int w, boolean h) { return 0; }
8: public int nested(int level) { return level+1; }
9:
10: public static void main(String[] outOfTheBox) {
11: System.out.print(new Dolls().nested());
12: } }
18: Comparator<String> c1 = (j, k) -> 0;
19: Comparator<String> c2 = (String j, String k) -> 0;
20: Comparator<String> c3 = (var j, String k) -> 0;
21: Comparator<String> c4 = (var j, k) -> 0;
22: Comparator<String> c5 = (var j, var k) -> 0;
public class Bunny {
static interface Rabbit { }
static class FlemishRabbit implements Rabbit { }
private static void hop(Rabbit r) {
System.out.print("hop");
}
private static void hop(FlemishRabbit r) {
System.out.print("HOP");
}
public static void main(String[] args) {
Rabbit r1 = new FlemishRabbit();
FlemishRabbit r2 = new FlemishRabbit();
hop(r1);
hop(r2);
} }
hophop
HOPhop
hopHOP
HOPHOP
10: var list = new ArrayList<Integer>();
11: list.add(10);
12: list.add(9);
13: list.add(8);
14:
15: var num = 9;
16: list.removeIf(x -> {int keep = num; return x != keep;});
17: System.out.println(list);
18:
19: list.removeIf(x -> {int keep = num; return x == keep;});
20: System.out.println(list);
[]
[8]
[8, 10]
[8, 9, 10]
[10, 8]
var babies = Arrays.asList("chick", "cygnet", "duckling");
babies.replaceAll(x -> { var newValue = "baby";
return newValue; });
System.out.println(babies);
[baby]
[baby, baby, baby]
[chick, cygnet, duckling]
[]
import java.util.*;
public final class Forest {
private final int flora;
private final List<String> fauna;
public Forest() {
this.flora = 5;
this.fauna = new ArrayList<>();
}
public int getFlora() {
return flora;
}
public List<String> getFauna() {
return fauna;
} }
public record Light(String type, float lumens) {
final static String DEFAULT_TYPE = "PAR";
public Light {
if(type == null)
throw new IllegalArgumentException();
else type = DEFAULT_TYPE;
}
public Light(String type) {
this.type = "B";
this.lumens = 10f;
}
public static void main(String[] p) {
final var bulb = new Light("A", 300);
System.out.print(bulb.type());
} }
null
A
PAR
public class Dress {
int size = 10;
default int getSize() {
display();
return size;
}
static void display() {
System.out.print("What a pretty outfit!");
}
private int getLength() {
display();
return 15;
}
private static void tryOn() {
display();
} }
getSize()
method does not compile.getLength()
method does not compile.tryOn()
method does not compile.private
interface method? (Choose two.)
static
methods to access instance methods.Snack
compile?
public abstract sealed class Snack permits Snack.Lollipop {
final static class Toast extends Snack {}
sealed static class Lollipop extends Snack {}
final class Treat extends Lollipop {}
abstract non-sealed class IceCream extends Snack {}
}
Snack
does not compile.package commerce;
public class Bank {
public static void withdrawal(int amountInCents) {}
public static void deposit(int amountInCents) {}
}
package employee;
// INSERT CODE HERE
public class Teller {
public void processAccount(int deposit, int withdrawal) {
withdrawal(withdrawal);
deposit(deposit);
} }
import static commerce.Bank.*;
import static commerce.Bank;
static import commerce.Bank.*;
static import commerce.Bank;
3.145.70.60