Читать книгу OCP Oracle Certified Professional Java SE 11 Developer Practice Tests - Jeanne Boyarsky - Страница 24

Chapter 3 Java Object‐Oriented Approach

Оглавление

THE OCP EXAM TOPICS COVERED IN THIS PRACTICE TEST INCLUDE THE FOLLOWING:

 Java Object‐Oriented ApproachDeclare and instantiate Java objects including nested class objects, and explain objects' lifecycles (including creation, dereferencing by reassignment, and garbage collection)Define and use fields and methods, including instance, static and overloaded methodsInitialize objects and their members using instance and static initialiser statements and constructorsUnderstand variable scopes, apply encapsulation and make objects immutableCreate and use subclasses and superclasses, including abstract classesUtilize polymorphism and casting to call methods, differentiate object type versus reference typeCreate and use interfaces, identify functional interfaces, and utilize private, static, and default methodsCreate and use enumerations

1 What is the output of the following application?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); } }3993The code does not compile because of line g1.The code does not compile because of line g2.None of the above.

2 Which of the following lines of code are not permitted as the first line of a Java class file? (Choose two.)import widget.*;// Widget Managerint facilityNumber;package sprockets;/** Author: Cid **/void produce() {}

3 Which of the following modifiers can be applied to an abstract method? (Choose two.)finalprivatepublicdefaultprotectedconcrete

4 What is the result of compiling and executing the following class?1: public class ParkRanger { 2: int birds = 10; 3: public static void main(String[] data) { 4: var trees = 5; 5: System.out.print(trees+birds); 6: } 7: }It compiles and outputs 5.It compiles and outputs 15.It does not compile.It compiles but throws an exception at runtime.

5 Fill in the blanks: The ___________________ access modifier allows access to everything the ___________________ access modifier does and more.package‐private, protectedprivate, package‐privateprivate, protectedprivate, publicpublic, privateNone of the above

6 Which set of modifiers, when added to a default method within an interface, prevents it from being overridden by a class implementing the interface?constfinalstaticprivateprivate staticNone of the above

7 Given the following application, fill in the missing values in the table starting from the top and going downward.package competition; public class Robot { static String weight = "A lot"; double ageMonths = 5, ageDays = 2; private static boolean success = true; public void main(String[] args) { final String retries = "1"; // P1 } }Variable TypeNumber of Variables Accessible at P1Class_____Instance_____Local_____2, 0, 12, 2, 11, 0, 10, 2, 1

8 Given the following code, what values inserted, in order, into the blank lines allow the code to compile? (Choose two.)_______ agent; public _______ Banker { private static _______ getMaxWithdrawal() { return 10; } }package, new, intpackage, class, longimport, class, null//, class, intimport, interface, voidpackage, class, void

9 Which of the following are correct? (Choose two.)public class Phone { private int size; // insert constructor here 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); } }The following is a valid constructor:public static Phone create(int size) { return new Phone(size); }The following is a valid constructor:public static Phone newInstance(int size) { return new Phone(); }The following is a valid constructor:public Phone(int size) { this.size=size; }The following is a valid constructor:public void Phone(int size) { this.size=size; }With the correct constructor, the output is 3.With the correct constructor, the output is 7.

10 Given the following class structures, which lines can be inserted into the blank independently that would allow the class to compile? (Choose two.)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()

11 What is the output of the 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‐The code does not compile.None of the above.

12 What access modifier is used to mark class members package‐private?defaultfriendprotectedprivateNone of the above

13 How many lines does the following code output?public class Cars { private static void drive() { static { System.out.println("static"); } System.out.println("fast"); { System.out.println("faster"); } } public static void main(String[] args) { drive(); drive(); } }One.Two.Three.Four.None of the above. The code does not compile.

14 Which statements about static interface methods are correct? (Choose three.)A static interface method can be final.A static interface method can be declared private.A static interface method can be package‐private.A static interface method can be declared public.A static interface method can be declared protected.A static interface method can be declared without an access modifier.

15 Fill in the blanks with the only option that makes this statement false: A(n) ______________ can access ______________ of the enclosing class in which it is defined.static nested class, static membersstatic nested class, instance membersmember inner class, static membersmember inner class, instance memberslocal class, instance members from within an instance methodanonymous class, instance members from within an instance method

16 What is the result of executing the following program?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)); } }152535One line does not compile.Two lines do not compile.The program compiles but throws an exception at runtime.

17 What statement best describes the notion of effectively final in Java?A local variable that is marked finalA static variable that is marked finalA local variable whose primitive value or object reference does not change after it is initializedA local variable whose primitive value or object reference does not change after a certain point in the methodNone of the above

18 What is the output of the Turnip class?package animal; 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()); } }35The code does not compile.The code compiles but throws an exception at runtime.None of the above.

19 What is the output of the following application?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"); } } }1212The code does not compile.The code compiles but throws an exception at runtime.None of the above.

20 Which statements about instance keywords are correct? (Choose two.)The that keyword can be used to read public members in the direct parent class.The this keyword can be used to read all members declared within the class.The super keyword can be used to read all members declared in a parent class.The that keyword can be used to read members of another class.The this keyword can be used to read public members in the direct parent class.The super keyword can be used in static methods.

21 Fill in the blanks: A class ____________ an interface and ______________ an abstract class. An interface ______________ another interface.extends, extends, implementsextends, implements, extendsextends, implements, implementsimplements, extends, extendsimplements, extends, implementsimplements, implements, extends

22 Suppose you have the following code. Which of the images best represents the state of the references 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: } }Option A.Option B.Option C.Option D.The code does not compile.None of the above.

23 What is the output of the following application?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()); } }75The code does not compile.The code compiles without issue, but the output cannot be determined until runtime.None of the above.

24 What is the output of the following application?package ai; interface Pump { void pump(double psi); } 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!The code does not compile because Bend is not a functional interface.The code does not compile because of the apply() method declaration.None of the above.

25 Which statement is true about encapsulation while providing the broadest access allowed?Variables are private, and methods are private.Variables are private, and methods are public.Variables are public, and methods are private.Variables are public, and methods are public.None of the above.

26 Fill in the blanks: The ___________________ access modifier allows access to everything the ___________________ access modifier does and more.package‐private, privateprivate, protectedprotected, publicprivate, package‐privateNone of the above

27 Which statement about the following interface is correct?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 } }The code compiles without issue.The code does not compile because of line k1.The code does not compile because of line k2.The code does not compile because of line k3.The code does not compile because of line k4.None of the above.

28 Which is the first line to fail to compile?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 }r1r2r3r4r5None of the above

29 Which modifier can be applied to an abstract interface method?finalinterfaceprotectedvoidNone of the above

30 What is the output of the 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,plantplant,bush,bushbush,plant,bushbush,bush,bushThe code does not compile.None of the above.

31 Which statements can accurately fill in the blanks in this table? (Choose two.)Variable TypeCan Be Called Within the Class from What Type of Method?InstanceBlank 1: _____________staticBlank 2: _____________Blank 1: an instance method onlyBlank 1: a static method onlyBlank 1: an instance or static methodBlank 2: an instance method onlyBlank 2: a static method onlyBlank 2: an instance or static method

32 What is the correct order of statements for a Java class file?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 statements

33 What is true of the following code? (Choose three.)1: class Penguin { 2: 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: } 13: } 14: }It compiles as is.It does not compile as is.Removing line 2 would create an additional compiler error.Removing line 2 would not create an additional compiler error.Removing the static modifier on line 3 would create an additional compiler error.Removing the static modifier on line 3 would not create an additional compiler error.

34 Which are true of the following? (Choose two.)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(); } }The code compiles.One line doesn't compile.Two lines don't compile.If any constructors and/or methods that do not compile are removed, the remaining code prints a.If the code compiles or if any constructors/methods that do not compile are removed, the remaining code prints ab.If the code compiles or if any constructors/methods that do not compile are removed, the remaining code prints aab.

35 Which of the following class types cannot be marked final or abstract?static nested class.Local class.Anonymous class.Member inner class.All of the above can be marked final or abstract.

36 Fill in the blanks: The ___________________ access modifier allows access to everything the ___________________ access modifier does and more. (Choose three.)package‐private, protectedpackage‐private, publicprotected, package‐privateprotected, publicpublic, package‐privatepublic, protected

37 Which is the first line containing a compiler error?var title = "Weather"; // line x1 var hot = 100, var cold = 20; // line x2 var f = 32, int c = 0; // line x3x1x2x3None of the above

38 How many of the following members of Telephone interface are public?public interface Telephone { static int call() { return 1; } default void dial() {} long answer(); String home = "555-555-5555"; }Zero.One.Two.Three.Four.The code does not compile.

39 Which best describes what the new keyword does?Creates a copy of an existing object and treats it as a new one.Creates a new primitive.Instantiates a new object.Switches an object reference to a new one.The behavior depends on the class implementation.

40 How many lines will not compile?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: }ZeroOneTwoThreeFourFive

41 Which of the following can include a static method in its definition? (Choose three.)InterfaceAnonymous classAbstract classMember inner classLocal classstatic nested class

42 What is the minimum number of lines that need to be removed to make this code compile?@FunctionalInterface public interface Play { public static void baseball() {} private static void soccer() {} default void play() {} void fun(); }1.2.3.4.The code compiles as is.

43 Fill in the blanks: A class that defines an instance variable with the same name as a variable in the parent class is referred to as ___________________ a variable, while a class that defines a static method with the same signature as a static method in a parent class is referred to as ___________________ a method.hiding, overridingoverriding, hidingmasking, maskinghiding, maskingreplacing, overridinghiding, hiding

44 What change is needed to make Secret well encapsulated?import java.util.*; public class Secret { private int number = new Random().nextInt(10); public boolean guess(int candidate) { return number == candidate; } }Change number to use a protected access modifier.Change number to use a public access modifier.Declare a private constructor.Declare a public constructor.Remove the guess method.None. It is already well encapsulated.

45 Which of the following are the best reasons for creating a public static interface method? (Choose two.)Allow static methods to access instance methods.Allow an interface to define a method at the class level.Provide an implementation that a class implementing the interface can override.Improve code reuse within the interface.Add backward compatibility to existing interfaces.Improve encapsulation of the interface.

46 What is the output of the following application?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()); } }TALLThe code does not compile because of line w1.The code does not compile because of line w2.The code does not compile for another reason.The code compiles, but the application does not produce any output at runtime.None of the above.

47 Which of the following is not a valid order for elements within a class?Constructor, instance variables, method declarationsInstance variables, static initializer constructor, method declarationsMethod declarations, instance variables, constructorInstance initializer, constructor, instance variables, constructorNone of the above

48 Which line of code, inserted at line p1, 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);

49 Which of the following is not a reason to use encapsulation when designing a class? (Choose two.)Improve security.Increase concurrency and improve performance.Maintain class data integrity of data elements.Prevent users from modifying the internal attributes of a class.Prevent variable state from changing.Promote usability by other developers.

50 Which statement about the following program is correct? (Choose two.)package ballroom; class Leader {} class Follower {} abstract class Dancer { public Leader getPartner() { return new Leader(); } abstract public Leader getPartner(int count); // u1 } public abstract class SwingDancer extends Dancer { public Leader getPartner(int x) { return null; } public Follower getPartner() { // u2 return new Follower(); // u3 } public static void main(String[] args) { new SwingDancer().getPartner(); // u4 } }The code does not compile because of line u1.The code does not compile because of line u2.The code does not compile because of line u3.The code does not compile because of line u4.At least three of the classes compile without issue.All of the classes compile without issue.

51 Which is not a true statement given this diagram? Assume all classes are public.Instance methods in the Blanket class can call the Flashlight class's turnOn().Instance methods in the Flashlight class can call the Flashlight class's replaceBulb().Instance methods in the Phone class can call the Blanket class's wash().Instance methods in the Tent class can call the Tent class's pitch().None of the above.

52 Given the diagram in the previous question, how many of the classes shown in the diagram can call the display() method?ZeroOneTwoThreeFour

53 Which of the following statements are correct? (Choose two.)Java allows multiple inheritance using two abstract classes.Java allows multiple inheritance using two interfaces.Java does not allow multiple inheritance.An interface can extend another interface.An interface can implement another interface.

54 Which statement about the following code is correct?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(); } }The code contains an invalid constant.The method getSize() does not compile.The method getLength() does not compile.The method tryOn() does not compile.The code compiles.None of the above.

55 What is the output of the following application?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); } }2357The code does not compile.None of the above.

56 What is the output of the following application?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 } }25The first line with a compiler error is line q1.The first line with a compiler error is line q2.The first line with a compiler error is line q3.

57 Given the following method signature, which classes can call it?void run(String government)Classes in other packagesClasses in the same packageSubclasses in a different packageAll classesNone of the above

58 Which is the first declaration to not compile?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; } }The CanBurrow interface does not compile.The HasHardShell interface does not compile.The Tortoise interface does not compile.The DesertTortoise interface does not compile.All of the interfaces compile.

59 Which is the first line to not compile?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 {} // m4Line m1Line m2Line m3Line m4None of the above

60 What is the output of the following code snippet?String tree = "pine"; int count = 0; if (tree.equals("pine")) { int height = 55; count = count + 1; } System.out.print(height + count);15556It does not compile.

61 Which of the following are valid comments in Java? (Choose three.)/****** TODO */# Fix this bug later' Error closing pod bay doors/ Invalid record //* Page not found */// IGNORE ME

62 Which of the following modifiers can both be applied to a method? (Choose three.)private and finalabstract and finalstatic and privateprivate and abstractabstract and staticstatic and protected

63 Given the following class, what should be inserted into the two blanks to ensure the class data is properly encapsulated?package storage; public class Box { public String stuff; __________ String __________() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } }private and getStuffprivate and isStuffpublic and getStuffpublic and isStuffNone of the above

64 How many rows of the following table contain an error?Interface memberMembership typeRequires method body?Static methodClassYesPrivate non‐static methodClassYesAbstract methodInstanceNoDefault methodInstanceNoPrivate static methodClassYesZeroOneTwoThreeFour

65 Fill in the blanks: ___________________ is used to call a constructor in the parent class, while ___________________ is used to reference a member of the parent class.super and this()super and super()super() and thissuper() and superNone of the above

66 What is the output of the Watch 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: } 7: public class Watch { 8: private String getType() { return "watch"; } 9: public String getName(String suffix) { 10: return getType() + suffix; 11: } 12: public static void main(String[] args) { 13: var watch = new Watch(); 14: var smartWatch = new SmartWatch(); 15: System.out.print(watch.getName(",")); 16: System.out.print(smartWatch.getName("")); 17: } 18: }smart watch,watchwatch,smart watchwatch,watchThe code does not compile.An exception is printed at runtime.None of the above.

67 What is the output of the 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); } }SequelTrilogyRemakeAdaptationnullNone of the above

68 Where can a final instance variable be assigned a value? (Choose three.)Instance initializerstatic initializerInstance methodOn the line it is declaredClass constructorstatic method

69 What is the output of the following code?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); } }hophopHOPhophopHOPHOPHOPThe code does not compile.

70 Which of the following results is not a possible output of this program?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.An ArrayIndexOutOfBoundsException is thrown at runtime.An IllegalArgumentException is thrown at runtime.All of the above are possible.

71 Which statement about encapsulation is not true?Encapsulation allows putting extra logic in the getter and setter methods.Encapsulation can use immutable instance variables in the implementation.Encapsulation causes two classes to be more tightly tied together.Encapsulation makes it easier to change the instance variables in the future.All of the above are true.

72 What is the output of the following application?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!The code does not compile.The code compiles, but the answer cannot be determined until runtime.

73 Which of the following statements about overriding a method are correct? (Choose three.)The return types must be covariant.The access modifier of the method in the child class must be the same or narrower than the method in the superclass.The return types must be the same.A checked exception thrown by the method in the parent class must be thrown by the method in the child class.A checked exception thrown by a method in the child class must be the same or narrower than the exception thrown by the method in the parent class.The access modifier of the method in the child class must be the same or broader than the method in the superclass.

74 How lines of the following code do not compile?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: } }None, they all compileOneTwoThreeFourFive or more

75 Of the following four modifiers, choose the one that is not implicitly applied to all interface variables.finalabstractstaticpublic

76 Given the following method, what is the first line that does not compile?public static void main(String[] args) { int Integer = 0; // k1 Integer int = 0; // k2 Integer ++; // k3 int++; // k4 int var = null; // k5 }k1k2k3k4k5

77 What is the result of compiling and executing the following class?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 } }The code does not compile due to line x.The code does not compile due to line y.3161

78 What is the output of the following application?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 FLURRY1 FLURRY0 Sunny1 SunnyThe code does not compile.None of the above.

79 Which of the following is not a true statement?The first line of every constructor is a call to the parent constructor via the super() command.A class is not required to have a constructor explicitly defined.A constructor may pass arguments to the parent constructor.A final instance variable whose value is not set when it is declared or in an initialization block should be set by the constructor.None of the above.

80 What can fill in the blank so the play() method can be called from all classes in the com.mammal and com.mammal.eland package, but not the com.mammal.gopher package?package com.mammal; public class Enrichment { ______ void play() {} }Leave it blank.privateprotectedpublicNone of the above.

81 What is the output of the Rocket program?package transport; class Ship { protected int weight = 3; private 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()+","+super.height); } public static final void main(String[] fuel) { new Rocket().printDetails(); } }2,53,45,23,5The code does not compile.None of the above.

82 Imagine you are working with another team to build an application. You are developing code that uses a class that the other team has not finished writing yet. You want to allow easy integration once the other team's code is complete. Which statements would meet this requirement? (Choose two.)An abstract class is best.An interface is best.Either of an abstract class or interface would meet the requirement.The methods should be protected.The methods should be public.The methods should be static.

83 Fill in the blank with the line of code that allows the program to compile and print 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()The code does not compile regardless of what is inserted into the blank.None of the above.

84 Which of the following properties of an enum can be marked abstract?The enum type definitionAn enum methodAn enum valueAn enum constructorNone of the above

85 How many lines does the following code output?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(); } }One.Two.Three.Four.Five.None of the above. The code does not compile.

86 Suppose 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.It can be used to read from bar.It can be used to write to bar.All of the above are possible.

87 The following diagram shows two reference variables pointing to the same 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.)The reference type of unknownBunny must be Bunny or a supertype of Bunny.The reference type of unknownBunny cannot be cast to a reference type of Bunny.The reference type of unknownBunny must be Bunny or a subclass of Bunny.If the reference type of unknownBunny is Bunny, it has access to all of the same methods and variables as myBunny.The reference type of unknownBunny could be an interface, class, or abstract class.If the reference type of unknownBunny is Object, it has access to all of the same methods and variables as myBunny without a cast.

88 Which of the following interface methods are inherited by classes that implement the interface? (Choose two.)private methodsprivate static methodsdefault methodsstatic methodsabstract methodsfinal methods

89 Which of these are functional interfaces?interface Lion { public void roar(); default void drink() {} String toString(); } interface Tiger { public void roar(); default void drink() {} int hashCode(); }LionTigerBoth Lion and TigerNeither is a functional interface.The code does not compile.

90 Given the following code, which lines when placed independently in the blank allow the code to compile and print 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();

91 How many of these methods 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_far(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); } }ZeroOneTwoThreeFourFive

92 What is the output of the following application?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 25 2 25 2 16 2 26 2 1The code does not compile.

93 Given that 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; } }LongIntegerLong or IntegerLong or NumberLong, Integer, or NumberNone of the above

94 What is the output of the 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()); } }rtirtThe code does not compile due to line g1.The code does not compile due to line g2.The code does not compile due to line g3.None of the above.

95 What is the output of the following program?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!An exception is thrown with a Too little! message.A different exception is thrown.The code does not compile because buryBone() is not used.The code does not compile because chaseTail() cannot declare any exceptions in the Puppy class.None of the above.

96 Which of the following are advantages of using enumerated types in Java, rather than static constant values? (Choose three.)Improve performance.Provide access to fixed set of constants whose values do not change during the course of the application.Provide a caller with a list of available values for a parameter within a method.Ensure consistency of data across an application.Add support for concurrency.Offer ability to create new enumerated values at runtime.

97 How do you force garbage collection to occur at a certain point?Calling System.forceGc()Calling System.gc()Calling System.requireGc()Calling GarbageCollection.clean()None of the above

98 Which changes made to the following class would help to properly encapsulate the data in the class?package shield; public class Protect { private String material; protected int strength; public int getStrength() { return strength; } public void setStrength(int strength) { this.strength = strength; } }Add a getter method for material.Add a setter method for material.Change the access modifier of material to protected.Change the access modifier of strength to private.None of the above.

99 Which are true statements about referencing variables from a lambda? (Choose two.)Instance and static variables can be used regardless of whether effectively final.Instance and local variables can be used regardless of whether effectively final.Instance variables and method parameters must be effectively final to be used.Local variables and method parameters must be effectively final to be used.Local and static variables can be used regardless of whether effectively final.Method parameters and static variables can be used regardless of whether effectively final.

100 Given the following two classes, each in a different package, which line inserted into the code allows the second class to compile?package commerce; public class Bank { public void withdrawal(int amountInCents) {} public 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;None of the above

101 Given the following structure, which snippets of code return true? (Choose three.)interface Friendly {} abstract class Dolphin implements Friendly {} class Animal implements Friendly {} class Whale extends Object {} public class Fish {} class Coral extends Animal {}new Coral() instanceof Friendlynull instanceof Objectnew Coral() instanceof Objectnew Fish() instanceof Friendlynew Whale() instanceof Objectnew Dolphin() instanceof Friendly

102 What is true of the following code?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()); } }It prints 20 20 20It prints 20 20 75It prints 20 21 75It prints 21 21 75It does not compile due to setNumDays().It does not compile for another reason.

103 What statement about the following interface is correct?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: }Line 2 does not compile.Line 3 does not compile.Line 4 does not compile.Line 5 does not compile.Line 6 does not compile.Line 7 does not compile.All of the lines compile.

104 What is the output of the following application?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); } }‐101The Provider class does not compile.The Bank class does not compile.None of the above.

105 How many lines need to be removed for this code to compile?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: } 13: }ZeroOneTwoThreeFourFive

106 Fill in the blanks: A class may be assigned to a(n) ___________________ reference variable automatically but requires an explicit cast when assigned to a(n) ___________________ reference variable.subclass, outer classsuperclass, subclassconcrete class, subclasssubclass, superclassabstract class, concrete class

107 Which statement about functional interfaces is incorrect?A functional interface can have any number of static methods.A functional interface can have any number of default methods.A functional interface can have any number of private static methods.A functional interface can have any number of abstract methods.A functional interface can have any number of private methods.All of the above are correct.

108 What are possible outputs of the following given that the comment on line X can be replaced by 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); } }05Either 0 or 5Any int valueDoes not compile

109 How many of the String 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; }NoneOneTwoThreeNone of the above

110 Suppose Panther and Cub are interfaces and neither contains any default methods. Which statements are true? (Choose two.)If Panther has a single abstract method, Cub is guaranteed to be a functional interface.If Panther has a single abstract method, Cub may be a functional interface.If Panther has a single abstract method, Cub cannot be a functional interface.If Panther has two abstract methods, Cub is guaranteed to be a functional interface.If Panther has two abstract methods, Cub may be a functional interface.If Panther has two abstract methods, Cub cannot be a functional interface.

111 A local class can access which type of local variables? (Choose two.)finalprivateeffectively finalstaticdefaultconst

112 What does the following output?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: } 13: }blockconstructorinstanceThe code does not compile.None of the above.

113 Which statement about the following interface is correct?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 (); } }The code compiles.The method produceSap() does not compile.The method getNumberOfRings() does not compile.The method growLeaves() does not compile.The method getHeight() does not compile.The code does not compile because it contains a cycle.

114 Which statements about a variable with a type of var are true? (Choose two.)The variable can be assigned null at any point in the program.The variable can be assigned null only after initial initialization.The variable can never be assigned null.Only primitives can be used with the variable.Only objects can be used with the variable.Either a primitive or an object can be used with the variable.

115 Assume there is a class Bouncer with a protected variable. Methods in which class can access this variable?Any subclass of Bouncer or any class in the same package as BouncerAny superclass of BouncerOnly subclasses of BouncerOnly classes in the same package as BouncerNone of the above

116 What is the output of the following application?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; } }8Line p1 contains a compiler error.Line p2 contains a compiler error.Another line of code contains a compiler error.None of the above.

117 Which can fill in the blank to make the code compile? (Choose two.)interface Australian {} interface Mammal {} ________________ Australian, Mammal {}class Quokka extendsclass Quokka implementsNeither A nor B. Only one interface can be specified.interface Quokka extendsinterface Quokka implementsNeither D nor E. Only one interface can be specified.

118 What is true of the following method?public void setColor(String color) { color = color; }It is a correctly implemented accessor method.It is a correctly implemented mutator method.It is an incorrectly implemented accessor method.It is an incorrectly implemented mutator method.None of the above.

119 Which of the following statements about calling this() in a constructor are true? (Choose three.)If arguments are provided to this(), then there must be a constructor in the class able to take those arguments.If arguments are provided to this(), then there must be a constructor in the superclass able to take those arguments.If the no‐argument this() is called, then the class must explicitly implement the no‐argument constructor.If super() and this() are both used in the same constructor, super() must appear on the line immediately after this().If super() and this() are both used in the same constructor, this() must appear on the line immediately after super().If this() is used, it must be the first line of the constructor.

120 What is the result of compiling and executing the following class?public class RollerSkates { static int wheels = 1; int tracks = 5; public static void main(String[] arguments) { RollerSkates s = new RollerSkates(); int feet=4, tracks = 15; System.out.print(feet + tracks + s.wheels); } }The code does not compile.451020

121 Which statements about the following program are correct? (Choose two.)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 } }The code does not compile because of line m1.The code does not compile because of line m2.The code does not compile because of line m3.The code does not compile because of line m4.The code does not compile because of line m5.The code does not compile because of line m6.

122 Which statements about top‐level and member inner classes are correct? (Choose three.)Both can be marked protected.Only top‐level classes can be declared final.Both can declare constructors.Member inner classes cannot be marked private.Member inner classes can access private variables of the top‐level class in which it is defined.Both can be marked abstract.

123 What is required to define a valid Java class file?A class declarationA package statementAn import statementA class declaration and package statementA class declaration and at least one import statementThe public modifier

124 How many objects are eligible for garbage collection right before the end of the main() 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: } }None.One.Two.Three.The code does not compile.

125 What is the output of the following application?package race; interface Drive { int SPEED = 5; default int getSpeed() { return SPEED; } } interface Hover { int MAX_SPEED = 10; default int getSpeed() { return MAX_SPEED; } } public class Car implements Drive, Hover { public static void main(String[] gears) { class RaceCar extends Car { @Override public int getSpeed() { return 15; } }; System.out.print(new RaceCar().getSpeed()); } }51015The code does not compile.The answer cannot be determined with the information given.

126 What is the output of the following application? (Choose two.)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: } 13: }23568

127 Fill in the blanks: It is possible to extend a(n) ______________ but not a(n) ______________. (Choose two.)interface, abstract classanonymous class, static nested classabstract class, enumenum, interfaceabstract class, interfacelocal class, anonymous class

128 How many lines of the following program do not compile?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: }ZeroOneTwoThreeMore than three

129 What is the output of the 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 final 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()); } }024The code does not compile due to line x1.The code does not compile due to line x2.The code does not compile due to line x3.

130 What can fill in the blank so the 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() {} }Leave it blank.privateprotectedpublicNone of the above.

131 How many cells in the following table are incorrect?TypeAllows abstract methods?Allows constants?Allows constructors?Abstract classYesYesNoConcrete classYesYesYesInterfaceYesYesYesZeroOneTwoThreeFour

132 Which statements are true about a functional interface? (Choose three.)It may contain any number of abstract methods.It must contain a single abstract method.It may contain any number of private methods.It must contain a single private method.It may contain any number of static methods.It must contain a single static method.

133 Which variables have a scope limited to a method?Interface variablesClass variablesInstance variablesLocal variables

134 What is a possible output of the following application?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) { Gift gift = new Gift(); gift.setContents(gift); gift.showPresent(); } }Your gift: wrap.Gift@29ca2745Your gift: Your gift:It does not compile.It compiles but throws an exception at runtime.

135 Which of the following are the best reasons for creating a default interface method? (Choose two.)Allow interface methods to be overloaded.Add backward compatibility to existing interfaces.Give an interface the ability to create final methods.Allow an interface to define a method at the class level.Improve code reuse among classes that implement the interface.Improve encapsulation of the interface.

136 How many compiler errors does the following code contain?package animal; interface CanFly { public void fly() {} } final class Bird { public int fly(int speed) {} } public class Eagle extends Bird implements CanFly { public void fly() {} }NoneOneTwoThreeFour

137 Which of the following statements is not true?An instance of one class may access an instance of another class's attributes if it has a reference to the instance and the attributes are declared public.An instance of one class may access package‐private attributes in a parent class, provided the parent class is not in the same package.An instance of one class may access an instance of another class's attributes if both classes are located in the same package and marked protected.Two instances of the same class may access each other's private attributes.All of the above are true.

138 What is the output of the following code?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(); } }hophopHOPhophopHOPHOPHOPThe code does not compile.

139 Which of the following are valid class declarations? (Choose three.)class _ {}class river {}class Str3@m {}class Pond2$ {}class _var_ {}class 5Ocean {}

140 What is the output of the 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.04.08.0The code does not compile.The code compiles but prints an exception at runtime.None of the above.

141 Given the following application, which diagram best represents the state of the 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); } }

142 What is the output of the following application?package zoo; public class Penguin { private int volume = 1; private class Chick { private static int volume = 3; void chick() { 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(); } }Honk(1)!Honk(3)!The code does not compile.The code compiles, but the output cannot be determined until runtime.None of the above.

143 Which can implement a functional interface?An anonymous classA top‐level classA lambda expressionAn anonymous class or a top‐level classA top‐level class or a lambda expressionAn anonymous class, a top‐level class, or a lambda expression

144 Fill in the blank with the line of code that allows the program to compile and print E at runtime.interface Fruit { public default char getColor() { return 'F'; } } interface Edible { public default char getColor() { return 'E'; } } 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()The code does not compile regardless of what is inserted into the blank.None of the above.

145 Given the following two classes, each in a different package, which line inserted into the code allows the second class to compile?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;

146 What is the output of the 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 vehicleDriving electric carDriving carThe code does not compile.The code compiles but produces a ClassCastException at runtime.None of the above.

147 What is the output of the following program?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‐tiThe code does not compile.None of the above.

148 Given the following class declaration, which options correctly declare a local variable containing an instance of the class?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; };The code does not compile regardless of what is placed in the blank.None of the above.

149 What is the output of the 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!‐papyrusReading is fun!‐cellulosenull‐papyrusnull‐celluloseThe code does not compile.None of the above.

150 What does the following print?interface Vehicle {} class Bus implements Vehicle {} public class Transport { public static void main(String[] args) { Bus bus = new Bus(); boolean n = null instanceof Bus; boolean v = bus instanceof Vehicle; boolean b = bus instanceof Bus; System.out.println(n + " " + v + " " + b); } }false false falsefalse false truefalse true truetrue false truetrue true falsetrue true true

151 How many rows of the following table contain an error?Interface memberOptional modifier(s)Required modifier(s)Private methodprivate‐Default methodpublicdefaultStatic methodpublic static‐Abstract methodpublicabstractZeroOneTwoThreeFour

152 What is the output of the following program?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); } }SleepyBashfulDocThe code does not compile.An exception is thrown at runtime.

153 What is the output of the following application?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); // j1 } }8The code does not compile because AddNumbers is not a functional interface.The code does not compile because of line j1.The code does not compile for a different reason.None of the above.

154 Which of the following variables are always in scope for the entire program once defined?Package variablesClass variablesInstance variablesLocal variables

155 What is the command to call one constructor from another constructor in the same class?construct()parent()super()this()that()

156 Which of the following statements about no‐argument constructors and inheritance are correct? (Choose two.)The compiler cannot insert a no‐argument constructor into an abstract class.If a parent class does not include a no‐argument constructor, a child class cannot declare one.If a parent class declares constructors but each of them take at least one parameter, then a child class must declare at least one constructor.The no‐argument constructor is sometimes inserted by the compiler.If a parent class declares a no‐argument constructor, a child class must declare a no‐argument constructor.If a parent class declares a no‐argument constructor, a child class must declare at least one constructor.

157 Fill in the blanks: ______________ allow Java to support multiple inheritance, and anonymous classes can ______________ of them.Abstract classes, extend at most oneAbstract classes, extend any numberInterfaces, implement at most oneInterfaces, implement any numberConcrete classes, extend at most oneNone of the above

158 What is the result of executing the 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 } }The code prints hop once.The code prints hop twice.The first compiler error is on line p1.The first compiler error is on line p2.The first compiler error is on line p3.

159 What is the minimum number of lines that need to be removed to make this code compile?@FunctionalInterface public interface Play { public static void baseball() {} private static void soccer() {} default void play() {} void fun(); void game(); void toy(); }1234The code compiles as is.

160 Which of the following are the best reasons for creating a private interface method? (Choose two.)Add backward compatibility to existing interfaces.Provide an implementation that a class implementing the interface can override.Increase code reuse within the interface.Allow interface methods to be inherited.Improve encapsulation of the interface.Allow static methods to access instance methods.

161 What is the result of executing the 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(); } }The code runs and prints baa!.The Sheep class does not compile.The Sounds class does not compile.Neither class compiles.

162 What is the output of the following application?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); } }568The code does not compile.

163 Given the following class declaration, what expression can be used to fill in the blank so that 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 engine = new Engine(); final public static void main(String[] feed) { System.out.print(new Racecar().engine.getSpeed()); } }Racecar.speedthis.speedthis.Racecar.speedRacecar.Engine.this.speedRacecar.this.speedThe code does not compile regardless of what is placed in the blank.

164 Which statements about static initializers are correct? (Choose three.)They cannot be used to create instances of the class they are contained in.They can assign a value to a static final variable.They are executed at most once per program.They are executed each time an instance of the class is created from a local cache of objects.They are executed each time an instance of the class is created using the new keyword.They may never be executed.

165 What is the output of the 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(); } }23451123451452313245The code does not compile.None of the above.

166 Given the following class declaration, which value cannot be inserted into the blank line that would allow the code to compile?package mammal; interface Pet {} public class Canine implements Pet { public ______ getDoggy() { return this; } }CanineListObjectPetAll of the above can be inserted.

167 Which statement about the following interface is correct?public interface Movie { String pass = "TICKET"; private void buyPopcorn() { purchaseTicket(); } public static int getDrink() { buyPopcorn(); return 32; } private static String purchaseTicket() { getDrink(); return pass; } }The code compiles.The code contains an invalid constant.The method buyPopcorn() does not compile.The method getDrink() does not compile.The method purchaseTicket() does not compile.The code does not compile for a different reason.

168 Which methods compile?private static int numShovels; private int numRakes; public int getNumShovels() { return numShovels; } public int getNumRakes() { return numRakes; }Just getNumRakes()Just getNumShovels()Both methodsNeither method

169 How many lines of the following class contain compilation errors?1: class Fly { 2: public Fly Fly() { return 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: } 9: }None.One.Two.Three.Four.The answer cannot be determined with the information given.

170 How many of the classes in the figure can write code that references the sky() method?NoneOneTwoThreeFour

171 For the diagram in the previous question, how many classes can write code that references the light variable?NoneOneTwoThreeFour

172 Given the following method signature, which classes cannot call it?protected void run(String government)All classes in other packagesAll classes in the same packageSubclasses in a different packageSubclasses in the same package

173 What is the output of the following application?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 GiantRobotGiantRobot DinosaurRobotDinosaurRobot DinosaurRobotThe code does not compile because of line y1.The code does not compile because of line y2.None of the above.

174 What is the output of the 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()); } }10204.0One line of the program does not compile.Two lines of the program do not compile.None of the above.

175 What is the output of the following application?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!The code does not compile.The code compiles but prints an exception at runtime.None of the above.

176 What is true of these two interfaces?interface Crawl { void wriggle(); } interface Dance { public void wriggle(); }A concrete class can implement both, but must implement wriggle().A concrete class can implement both, but must not implement wriggle().A concrete class would only be able to implement both if the public modifier were removed but must implement wriggle().If the public modifier were removed, a concrete class can implement both, but must not implement wriggle().None of the above.

177 Which of these are functional interfaces?interface Lion { public void roar(); default void drink() {} boolean equals(Lion lion); } interface Tiger { public void roar(); default void drink() {} String toString(String name); }LionTigerBoth Lion and TigerNeither is a functional interface.The code does not compile.

178 How many lines of the following class contain a compiler error?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; } 18: }NoneOneTwoThreeMore than three

179 What is true of the following method?public String getColor() { return color; }It is a correctly implemented accessor method.It is a correctly implemented mutator method.It is an incorrectly implemented accessor method.It is an incorrectly implemented mutator method.None of the above.

180 Which statement is true?You can always change a method signature from call(String[] arg) to call(String… arg) without causing a compiler error in the calling code.You can always change a method signature from call(String… arg) to call(String[] arg) without causing a compiler error in the existing code.Both of the above.Neither of the above.

181 What are two motivations for marking a class final? (Choose two.)Guarantee behavior of a classAllow the class to be extendedImprove securitySupport polymorphismImprove performanceEnsure the contents of the class are immutable

182 Which statement about the following interface is correct?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(); } }The code compiles.The method enterAtmosphere() does not compile.The method getCircumference() does not compile.The method leaveOrbit() does not compile.The code does not compile for a different reason.None of the above.

183 Fill in the blanks: ___________________ methods always have the same name but a different list of parameters, while ___________________ methods always have the same name and the same return type.Overloaded, overriddenInherited, overriddenOverridden, overloadedHidden, overloadedOverridden, hiddenNone of the above

184 What is the output of the following program?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,‐112,213,‐1Exactly one line of this class does not compile.Exactly two lines of this class do not compile.None of the above.

185 Suppose you have the following code. Which of the images best represents the state of the references right before the end of the 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: } 23: }Option A.Option B.Option C.Option D.The code does not compile.None of the above.

186 Which statement about a no‐argument constructor is true?The Java compiler will always insert a default no‐argument constructor if you do not define a no‐argument constructor in your class.For a class to call super() in one of its constructors, its parent class must explicitly implement a no‐argument constructor.If a class extends another class that has only one constructor that takes a value, then the child class must explicitly declare at least one constructor.A class may contain more than one no‐argument constructor.

187 Which variable declaration is the first line not to compile?public class Complex { class Building {} 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; } }b3h2b4h3All of the lines compile.

188 What is the output of the following application?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: } }Spoiled!Yummy!The application completes without printing anything.One line of this application fails to compile.Two lines of this application fail to compile.None of the above.

189 Which of the following statements about functional interfaces is true?It is possible to define a functional interface that returns two data types.It is possible to define a primitive functional interface that uses float, char, or short.All functional interfaces must take arguments or return a value.None of the primitive functional interfaces includes generic arguments.None of these statements is true.

190 What is the result of executing the 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‐tortoiseinit‐hareThe first line with a compiler error is line x1.The first line with a compiler error is line x2.The code does not compile due to a different line.The code throws an exception.

191 How many lines of the following program do not compile?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) { int width = 5; class ParkVisit { int getValue() { return width + fun; } } System.out.print(new ParkVisit().getValue()); } }ZeroOneTwoThreeMore than three

192 What is the result of executing the Sounds program?// Sheep.java package com.mammal; public class Sheep { default void baa() { System.out.println("baa!"); } default 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(); } }The code runs and prints baa!.The Sheep class does not compile.The Sounds class does not compile.Neither class compiles.

193 What is the best reason for marking an existing static method private within in an interface?It allows the method to be overridden in a subclass.It hides the secret implementation details from another developer using the interface.It improves the visibility of the method.It ensures the method is not replaced with an overridden implementation at runtime.It allows the method to be marked abstract.Trick question! All static methods are implicitly private within an interface.

194 What is the output of the following application?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; } }568The code does not compile.

195 What is the result of compiling and executing the following class?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"); } }redpurpleblueIt does not compile.

196 Given that 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; } }ObjectIntegerShortNumberNone of the above

197 Which statements about abstract classes and methods are correct? (Choose three.)An abstract class can be extended by a final class.An abstract method can be overridden by a final method.An abstract class can be extended by multiple classes directly.An abstract class can extend multiple classes directly.An abstract class cannot implement an interface.An abstract class can extend an interface.

198 Given the following enum declaration, how many lines contain compilation errors?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(); }ZeroOneTwoThreeMore than three

199 Which statements about Java classes are true? (Choose three.)A Java class file may include more than one package statement.A Java class file may include more than one import statement.A Java class file may contain more than one comment.Any instance fields within a class must be defined after the class name.Any instance fields within a class must be defined before the class name.Java supports macros, in which fragments of code within a class may be defined inside a Java file, separate from any top‐level type declaration.

200 What is the result of executing the 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 } } The code prints hop once.The code prints hop twice.The first compiler error is on line p1.The first compiler error is on line p2.The first compiler error is on line p3.

201 Which of the following is not an attribute common to both abstract classes and interfaces?They both can contain abstract methods.They both can contain public methods.They both can contain protected methods.They both can contain static variables.

202 Given the following class, which method signature could be successfully added to the class as an overloaded version of the findAverage() method?public class Calculations { public Integer findAverage(int sum) { return sum; } }public Long findAverage(int sum)public Long findAverage(int sum, int divisor)public Integer average(int sum)private void findAverage(int sum)

203 Which of the following is a valid method name in Java? (Choose two.)Go_$Outside$2()have‐Fun()new()9enjoyTheWeather()$sprint()walk#()

204 Fill in the blanks: A functional interface must contain or inherit ______________ and may optionally include ______________.at least one abstract method, the @Override annotationexactly one method, static methodsexactly one abstract method, the @FunctionalInterface annotationat least one static method, at most one default methodNone of the above

205 Fill in the blank with the line of code that allows the program to compile and print 15 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()The code does not compile regardless of what is inserted into the blank.None of the above.

206 What is the output of the following program?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‐The code does not compile.None of the above.

207 Given the following two classes in the same package, what is the result of executing the 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.0The Kitten class does not compile.The Hug class does not compile.The Kitten and Hug classes do not compile.None of the above.

208 Which expressions about enums used in switch statements are correct? (Choose two.)The name of the enum type must not be used in each case statement.A switch statement that takes a enum value may not use ordinal() numbers as case statement matching values.The name of the enum type must be used in each case statement.Every value of the enum must be present in a case statement.A switch statement that takes a enum value can use ordinal() numbers as case statement matching values.Every value of the enum must be present in a case statement unless a default branch is provided.

209 What is the output of the following application?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 105 10The code does not compile because of line n1.The code does not compile because of line n2.The code does not compile because of line n3.The code does not compile because of line n4.

210 What is the result of executing the Tortoise program?// Hare.java package com.mammal; public class Hare { public void init() { System.out.print("init-"); } private 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‐tortoiseinit‐hareThe first line with a compiler error is line x1.The first line with a compiler error is line x2.The code does not compile due to a different line.The code throws an exception.

211 What is the result of executing the Sounds program?// Sheep.java package com.mammal; public class Sheep { private void baa() { System.out.println("baa!"); } private static 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(); } }The code runs and prints baa!.The Sheep class does not compile.The Sounds class does not compile.Neither class compiles.

212 What is the output of the 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()); } }510The code does not compile.The code compiles but produces a ClassCastException at runtime.None of the above.

213 Which statements about the following Twins class are true? (Choose three.)package clone; interface Alex { default void write() { System.out.print("1"); } static void publish() {} void think(); private int process() { return 80; } } interface Michael { default void write() { System.out.print("2"); } static void publish() {} void think(); private int study() { return 100; } } public class Twins implements Alex, Michael { void write() { System.out.print("3"); } static void publish() {} void think() { System.out.print("Thinking…"); } }The class fails to compile because of the write() method.The class fails to compile because of the publish() method.The class fails to compile because of the think() method.All of the methods defined in the Alex interface are accessible in the Twins class.All of the methods defined in the Michael interface are accessible in the Twins class.The Twins class cannot be marked abstract.

214 Given the following program, what is the first line to fail to compile?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: } 9: }Line 2Line 4Line 5Line 6Line 7All of the lines compile

215 What is the output of the following application?package prepare; public class Ready { protected static int first = 2; private 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, 55, 102, 10The code does not compile because of the GetSet class declaration.The code does not compile for another reason.

216 Which of the following are true about the following code? (Choose two.)public class Values { static ____ defaultValue = 8; static ____ DEFAULT_VALUE; public static void main(String[] args) { System.out.println(defaultValue + DEFAULT_VALUE); } }When you fill in both blanks with double, it prints 8.00.0When you fill in both blanks with double, it prints 8.0When you fill in both blanks with int, it prints 8When you fill in both blanks with int, it prints 80When you fill in both blanks with var, it prints 8When you fill in both blanks with var, it prints 80

217 How many Gems objects are eligible for garbage collection right before the end of the main() method?public class Gems { public String name; public Gems(String name) { this.name = 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; } }NoneOneTwoThreeFourThe code does not compile

218 How many lines of the following program contain compilation errors?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); } }NoneOneTwoThree

219 What is the output of the following application?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); } }5The code does not compile due to an invalid cast.The code does not compile for a different reason.The code compiles but throws a ClassCastException at runtime.

220 Which statement about the 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 } }It compiles and prints 6.The code does not compile because of line k1.The code does not compile because of line k2.The code does not compile because of line k3.The code does not compile because of line k4.None of the above.

OCP Oracle Certified Professional Java SE 11 Developer Practice Tests

Подняться наверх