Sei sulla pagina 1di 20

6.

methods encapsulation }
public static int get(int n) {
int fact = get();
1 for (int i = n; i > 1; i--) {
Given: fact *= i;
}
class Job { return fact;
private String name; }
private String[] reqs; public static int get(int n, int k)
public Job(String name, String... {
reqs) { return get(n) / get(n-k);
this.name = name; }
this.reqs = reqs; }
}
public void post() {/*Implementation Which code line will generate the output 120?
omitted*/}
private void post(char[] rawData) System.out.print(Factorial.get())
{/*Implementation omitted*/} ;
}
System.out.print(Factorial.get(5)
class Programmer extends Job { );
private String[] languages;
public Programmer(String name, System.out.print(Factorial.get(10
String... reqs) {super(name, reqs);} ));
public void post(String language) {
//Insert code here System.out.print(Factorial.get(10
} ,5));
}

Which statement, when inserted in the code, will 4


compile? Given:
post();
public class CardDeck {
post(language.toCharArray()); public CardDeck() {/*Implementation
omitted*/}
this(); public CardDeck (int suits)
{/*Implementation omitted*/}
this(languages.toCharArray()); public CardDeck (int suits, boolean
includeJokers) {/*Implementation
omitted*/}
2 }
Which statement is true about constructor
overloading? Which constructor is the default constructor?
A default constructor can be overloaded
CardDeck()
in the same class.
A default constructor can be overloaded CardDeck (int)
in a subclass.
CardDeck (int, boolean)
The constructor must use a different
name. Not provided.
The constructor must use the this
keyword. 5
Given:
3
Given: public class VarScope {
static int var;
public class Factorial { public static void main (String[]
public static int get() { args) {
return 1; int var = 9;
1
printVar(); overloadedMethod(10.5);
}
public static void printVar() { Which two statements are true about matching
int var = 10; overloaded methods?
//insert code here An overloaded method that declares a
} float parameter may match.
}
An overloaded method that declares a
Which statement should be inserted in the code Double parameter may match.
to output 0? An overloaded method that declares an
System.out.print(var); Object parameter may match.
An overloaded method that declares a
System.out.print(VarScope.var); float return type may match.
System.out.print(main.var); An overloaded method that declares a
Double return type may match.
System.out.print(main().var);
An overloaded method that declares an
Object return type may match.
6
Given:
8
public class CardHand { Which access modifier will permit access to class
public Card[] cards; members only from subclasses and other classes
public int handValue; in the same package?
private
public CardHand(Card... cards) {
this.cards = cards; protected
for (Card c: cards) {
public
handValue += c.getVal();
} no modifier
}
private int getVal() {return
handValue;} 9
} Given:

Which two statements are true about public class OutputSuperClass {


encapsulation in the CardHand class? public OutputSuperClass() {
If the handValue field is invariant, then System.out.println("Super");
the cards field should be declared with }
}
the modifier private.
If the handValue field is invariant, then public class OutputSubClass extends
the cards and handValue fields should OutputSuperClass {
be declared with the modifier private. public OutputSubClass () {
System.out.println("Sub 1");
If the handValue field is invariant, then
}
the cards and handValue fields and public OutputSubClass (int x) {
constructor should be declared with the System.out.println("Sub 2");
modifier private. }
The getVal method should be declared public OutputSubClass (int x, int y)
with the modifier public. {
System.out.println("Sub 3");
The class should be declared with the }
modifier private. public static void main(String[]
args) {
7 new OutputSubClass(1);
Given the following code line: }
}

2
An exception is thrown at runtime.
What is the result?
Sub 2
12
Sub 3 Given the following code fragment:
Super public class StandardMethods {
Sub 1 public static void
Super printPerimeter(double... sides) {
Sub 2 double result = 0;
for (double side: sides) {
result += side;
10
}
Which access modifier will permit access to class System.out.println("Perimeter is " +
members only from the same package? result);
private }
}
protected
Assuming the given code is in the same package,
public
which two code lines will compile?
no modifier StandardMethods.printPerimeter();

StandardMethods.printPerimeter(7.
11 5, 9.8, 11);
Given:
double perimeter =
class StandardMethods { StandardMethods.printPerimeter();
private StandardMethods() { double perimeter =
System.out.println("Constructor StandardMethods.printPerimeter(7.
invoked!"); } 5, 9.8, 11);
public static void
printPerimeter(double... sides) {
double result = 0; 13
for (double side: sides) { Which statement is true about passing arguments
result += side; to a method?
} If the argument is an object reference,
System.out.println("Perimeter is " + then the method will work with a copy of
result); that object.
}
If the argument is a primitive value, then
}
the method will work with the original
class MainClass {
public static void main(String[] value.
args) { If the argument is a primitive value, then
new any modifications to the original value
StandardMethods().printPerimeter(5,5 will not persist after the method returns.
); If the argument is an object reference,
} then any modifications to the original
} object will be discarded after the method
returns.
What is the result?
Constructor invoked!
14
Perimeter is 10.0 Given the following code line:

Constructor invoked! printToConsole("Cup of Java with a


Perimeter is 10.0 shot of espresso");
Compilation fails.
Which overloaded method is invoked?

3
void printToConsole() {
System.out.println("Hello, 16
world!"); Given:
}
void printToConsole(StringBuffer public class PrinterClass {
buffer) { private String arg;
System.out.println(buffer.toStrin public PrinterClass() {
g()); System.out.println("no args"); }
} public PrinterClass(String arg) {
this();
void printToConsole(Integer
this.arg = arg;
intObj) {
System.out.println("arg");
System.out.println("My number is
}
" + intObj.toString());
public void print() {
}
System.out.println(arg);
void printToConsole(Object obj) { }
System.out.println("My object is public static void main(String[]
" + obj.toString()); args) {
} new PrinterClass("val").print();
}
15 }
Given:
What is the result?
public class Pedometer { arg
private String units;
private double stride; val
public Pedometer(String units) { arg
this.units = units; val
}
} no args
arg
Which code fragment correctly overloads the val
constructor?
public Pedometer (double stride) 17
{ Given:
this("inches");
this.stride = 25; class CardDeck {
} public CardDeck get(int suits,
public Pedometer (String units, boolean includeJokers) { /*code
double stride) { omitted*/ }
super("inches"); }
super.stride = 25;
} Which change will prevent other classes from
directly instantiating the CardDeck class?
public static Pedometer init() {
Pedometer ped = new Adding the private modifier to the class.
Pedometer("inches");
ped.stride = 25; Adding the protected modifier to the
return ped; class.
} Adding a parameterless constructor with
public static Pedometer the private modifier to the class.
init(String units, double stride) Adding a parameterless constructor with
{ no modifier to the class.
Pedometer ped = new
Changing the public modifier to
Pedometer(units);
ped.stride = stride; protected on the get method.
return ped; Changing the public modifier to
} private on the get method.
4
}
18 }
Given:
What is the result?
class Job { arg
private String name;
private String[] reqs; arg
public Job(String name, String... null
reqs) { no args
this.name = name;
this.reqs = reqs; no args
} null
public void post() {/*Implementation
omitted*/} 20
//insert code here Which statement is true about default
} constructors?
class Programmer extends Job { Default constructors include only a single
private String language; parameter.
public Programmer(String name, Default constructors include an
String... reqs) {super(name, reqs);} invocation of the superclass.
public void post(String language) { All classes are provided a default
post(); constructor by the compiler.
post(language.toCharArray());
} Superclass constructors automatically
} invoke default constructors of
subclasses.
Which method, when inserted in the code, will
compile? 21
private void post(char[] rawData) Given:
{/*Implementation omitted*/}
protected void post(char[] public class Java7 {
rawData) {/*Implementation
omitted*/} static int modify (Integer i) {
i += 10;
public void post(String rawData) return i + 10;
{/*Implementation omitted*/} }
void post(String rawData) public static void main(String[]
{/*Implementation omitted*/} args) {
Integer i = 10;
//insert code here
19
}
Given: }
public class PrinterClass {
Which statement(s) should be inserted in the
private String arg;
public PrinterClass() { code to output 20?
System.out.println("no args"); } System.out.println(modify(i));
public PrinterClass(String arg) {
System.out.println(modify(i +
this();
10));
this.arg = arg;
System.out.println("arg"); modify(i); System.out.println(i);
}
public void print() { modify(i); System.out.println(i +
System.out.println(arg); 10);
}
public static void main(String[] 22
args) { Given:
new PrinterClass().print();
5
public class Pedometer { Sub 1
private double stride;
Super
private double[] measurements;
Sub 3
}

Which code fragment is a method that meets 24


good encapsulation principles? Given:
public void getStride(double
stride) { public class Container {
stride = this.stride; ArrayList<Integer> compartments;
} private int totalItems;
public Container(int
public void getStride(double
numCompartments) {
stride) {
compartments = new
this.stride = stride;
ArrayList<>(numCompartments);
}
}
public double[] getMeasurements() //Other code omitted
{ }
return this.measurements;
} This class is intended to calculate the total
public double[] getMeasurements() number of items within each compartment. Which
{ statement is true about encapsulation in the
return measurements.clone(); Container class?
} This class is properly encapsulated, but
the access modifier on the constructor
23 should be changed to private.
Given: This class is properly encapsulated, but
the access modifier on the
public class OutputSuperClass { compartments field should be changed
public OutputSuperClass() { to public.
System.out.println("Super");
} This class is poorly encapsulated. The
} totalItems field should be calculated in
the constructor and in any methods that
public class OutputSubClass extends modify the compartments field.
OutputSuperClass { This class is poorly encapsulated. The
public OutputSubClass () { compartments field should be set in any
System.out.println("Sub 1"); methods that modify the totalItems
}
field.
public OutputSubClass (int x) {
System.out.println("Sub 2");
} 25
public OutputSubClass (int x, int y) Given the following code fragment:
{
System.out.println("Sub 3"); public class StandardMethods {
} public static double
public static void main(String[] getSurfaceArea(double width, double
args) { height, double length) {
new OutputSubClass(1,2); return 2 * (width * length + height
} * length + height * width);
} }
}
What is the result?
Sub 1 Assuming the given code is in the same package,
which two code lines will compile?
Sub 3 StandardMethods.getSurfaceArea(8.
5);
Super

6
code, demonstrate good encapsulation
StandardMethods.getSurfaceArea(8.
5,11); principles?
Suit suit;
StandardMethods.getSurfaceArea(8.
5,11, 1.5); Color color;

double surfaceArea = public Suit suit;


StandardMethods.getSurfaceArea(8.
public Color color;
5);
double surfaceArea = private Suit suit;
StandardMethods.getSurfaceArea(8.
5,11); private Color color;
double surfaceArea =
StandardMethods.getSurfaceArea(8. 28
5,11, 1.5); Given the code:

26 public class VarScope {


public int i1;
Given:
public static int i2;
public class Circle { }
public double
getCircumference(double radius ) { Given the output:
return java.lang.Math.PI * 2 *
radius; 10 + 5 = 15
}
public static double getArea(double Which two code fragments will generate the
radius) { required output?
return java.lang.Math.PI * radius * VarScope v1 = new VarScope();
radius; VarScope v2 = new VarScope();
} v1.i1 = 10; v2.i1 = 5;
} System.out.format("%d + %d = %d",
v1.i1, v2.i1, v1.i1 + v2.i1);
Which two code fragments will fail compilation? VarScope v1 = new VarScope();
Circle.getCircumference(10.5); VarScope v2 = new VarScope();
v1.i2 = 10; v2.i2 = 5;
new System.out.format("%d + %d = %d",
Circle().getCircumference(10.5); v1.i2, v2.i2, v1.i2 + v2.i2);
double c = VarScope v1 = new VarScope();
Circle.getCircumference(10.5); VarScope v2 = new VarScope();
Circle.getArea(5.5); v1.i1 = 10; v2.i2 = 5;
System.out.format("%d + %d = %d",
new Circle().getArea(5.5); v1.i1, v1.i2, v1.i1 + v1.i2);

double a = new VarScope v1 = new VarScope();


Circle().getArea(5.5); VarScope v2 = new VarScope();
v1.i1 = 10; v2.i1 = 5;
System.out.format("%d + %d = %d",
27 v1.i2, v1.i2, v1.i2 + v1.i2);
Given:

public class Card {


29
enum Suit {CLUB, DIAMOND, HEART, Which statement is true about applying
SPADE} encapsulation principles to a class?
enum Color {BLACK, RED} The default modifier should be private
//add code here for all fields.
} The default modifier should be
protected for all fields.
Which two field declarations, when inserted in the
7
Accessor methods should return direct 32
references to field objects. Given:
Mutator methods should return direct
references to field objects. public class Java7 {

static int modify (int i) {


30 i += 10;
Given: return i + 10;
}
public int combine (int... ints) { public static void main(String[]
//implementation omitted args) {
} int i = 10;
//insert code here
Which code fragment correctly overloads the }
combine method? }
private Object combine (int...
ints) { Which statement(s) should be inserted in the
//implementation omitted code to output 30?
} System.out.println(modify(i));
public static double combine
System.out.println(modify(i +
(double... doubles) {
10));
//implementation omitted
} modify(i); System.out.println(i);
public static int combine (int... modify(i); System.out.println(i +
int2s) { 10);
//implementation omitted
}
33
private double combine (int...
ints) { Which statement is true about varargs when
//implementation omitted specifying method parameters?
} Arguments are accessible as
enumeration values.
31 Arguments can consist of different data
types.
Given:
Valid invocation requires at least one
class Fruit {} argument value.
Valid invocation can have zero
class Coconut extends Fruit { arguments.
Coconut(int size) {}
Coconut(int size, String region)
{this(size);} 34
} Which two characteristics distinguish overloaded
methods?
Which three lines of code invoke a default Access modifiers
constructor?
new Fruit(); Method name

new Coconut(); Return type

new Fruit(3); Parameter number

new Coconut(3); Parameter data types

new Fruit(3, "Costa Rica");

new Coconut(3, "Costa Rica");

8
7. inheritance public static void main(String[]
args) {
System.out.println(new
1 Card(Suit.CLUBS, 2));
Given: }
}
public interface ShiftCipher {
public String encrypt(String Which statement(s), when inserted in the code,
plaintext,int shift); will generate the output 2 of CLUBS?
public String decrypt(String
ciphertext,int shift); super(suit, value);
} this(suit, value);
Which two class definitions are valid? super.suit = suit; super.value =
public abstract class value;
CaesarCipher extends ShiftCipher this.suit = suit; this.value =
{} value;
public abstract class
CaesarCipher implements 3
ShiftCipher {} Given:
public class CaesarCipher extends
ShiftCipher {} public class Job {
public class CaesarCipher public void post() {/*Implementation
implements ShiftCipher {} omitted*/}
protected void post(char[] rawData)
public class CaesarCipher extends {/*Implementation omitted*/}
ShiftCipher { }
public String encrypt(String
plaintext, int shift) {/* Which two are valid declarations of a method that
implementation omitted */}
overrides post?
public String decrypt(String
ciphertext, int shift) {/* public void post(String language)
implementation omitted */} private void post(String
} language)
public class CaesarCipher
implements ShiftCipher { public void post()
public String encrypt(String public void post(char[] data)
plaintext, int shift) {/*
implementation omitted */} private void post(char[] data)
public String decrypt(String
ciphertext, int shift) {/* public String post()
implementation omitted */}
}
4
Given:
2
Given: public interface Job {
public void post();
public enum Suit {CLUBS, DIAMONDS, void post(char[] rawData);
HEARTS, SPADES} }
public class Card {
private Suit suit; Which two are valid declarations of methods that
private int value; implement post?
public Card(Suit suit, int value) {
//insert code here public void post(String language)
} private void post(String
public String toString() { language)
return value + " of " + suit;
}
9
public void post() }
public interface HourlyWorker {
public void post(char[] data) public static double
minimum_wage;
private void post(char[] data)
public void performWork(double
public String post() hours);
}
5
public interface HourlyWorker {
Which statement is true about abstract classes? public static final double
An abstract class may contain only minimum_wage = 7.25;
abstract methods. public abstract HourlyWorker();
An abstract class may contain both class public abstract void
and instance members. performWork(double hours);
}
Abstract methods may be declared with
the final modifier. public interface HourlyWorker {
public static final double
Abstract methods may be declared with minimum_wage = 7.25;
the private modifier. public void performWork(double
hours) {
6 //implementation
Which class is a valid superclass for defining a }
custom type wrapper? }
Byte
9
Double Given:
Float public class OutputSuperClass {
OutputSuperClass() {
Integer
System.out.println("Super");
Long }
}
Number
public class OutputSubClass extends
Short OutputSuperClass {
OutputSubClass () {
System.out.println("Sub 1");
7 }
Given the code fragment: OutputSubClass (int x) {
//insert code here
Readable reader = new System.out.println("Sub 2");
BufferedReader(new }
FileReader("file.txt")); }

Which is the object type for reader? Which statement, when inserted in the code, will
String generate the output Sub 1?
this();
Readable
super();
FileReader
this.OutputSubClass();
BufferedReader
super.OutputSubClass();
8
Which type defines a valid interface? 10
public interface HourlyWorker { Which two statements are true about the super
double minimum_wage = 7.25; keyword?
void performWork(double hours);
10
The super keyword can access all plaintext);
superclass constructors from a subclass. public byte[] decrypt(byte[]
ciphertext);
The super keyword can access all }
members of a superclass from a
subclass. public class CaesarCipher extends
ShiftCipher {
The super keyword can access all public String encrypt(String
constructors in a superclass or subclass. plaintext, int shift)
The super keyword can access all {/*implementation omitted*/}
members in a superclass or subclass. public String decrypt(String
ciphertext, int shift) {/*
The super keyword can invoke implementation omitted */}
superclass methods in overridden }
methods in a subclass.
public abstract class
The super keyword can invoke CaesarCipher implements
superclass methods in overloaded ShiftCipher {
methods in a subclass. public String
encryptAndDecrypt(String txt)
11 {/*implementation omitted*/}
Which statement is true about exceptions when }
implementing interface methods? public class CaesarCipher
Implementation methods must specify an implements ShiftCipher {
exception if specified by the interface public byte[] encrypt(byte[]
method. plaintext, int shift)
{/*implementation omitted*/}
Implementation methods must specify the public byte[] decrypt(byte[]
same exception as specified by the ciphertext, int shift) {/*
interface method. implementation omitted */}
Implementation methods can specify a }
subclass of the exception specified by
the interface method.
13
Implementation methods can specify a Which statement is true about reference and
superclass of the exception specified by object types?
the interface method. The reference type corresponds to the
instantiated class.
12 The object type corresponds to the type
Given: in the variable declaration.

public interface ShiftCipher { The reference type determines which


String encrypt(String plaintext,int members are accessible.
shift); The object type determines which hidden
String decrypt(String ciphertext,int members are accessible.
shift);
}
14
Which statement is true about reference type
Which two types use ShiftCipher correctly?
casting?
public interface AutoShiftCipher
Reference type casting is only valid
implements ShiftCipher {
between subtypes.
public byte[] encrypt(byte[]
plaintext); Reference type casting is only valid
public byte[] decrypt(byte[] between supertypes.
ciphertext); The target type must be the object type or
} a valid subtype.
public interface AutoShiftCipher The target type must be the object type or
extends ShiftCipher { a valid supertype.
public byte[] encrypt(byte[]

11
15 Given the code fragment:
Given:
CharSequence obj = new StringBuilder
public class SuperString { ( new String("String") );
public String toString() {
return "Super String 1"; Which is the reference type?
} Object
public Object toString(String str) {
return "Super String 2"; String
}
} CharSequence

class SubString extends SuperString StringBuilder


{
public String toString() { 18
return "Sub String 1";
Given:
}
public String toString(String str) {
public class SuperString {
return "Sub String 2";
public String toString() {
} return "Super String";
public static void main(String[] }
args) { public Object toString(String str) {
SuperString string = new
return "Super " + str;
SubString(); }
System.out.println(string); }
}
}
class SubString extends SuperString
{
What is the result? public String toString() {
Sub String 1 return "Sub String";
}
Sub String 2 public String toString(String str) {
return "Sub " + str;
Super String 1 }
Super String 2 }

Compilation fails. Which two statements will generate the output


Super String?
An exception is thrown at run time. System.out.println(new
SubString().toString());
16 System.out.println(new
Which statement is true about reference and SuperString().toString("String"))
object types? ;
The reference type corresponds to the System.out.println(((Object) new
instantiated class. SubString()).toString());
The object type corresponds to the type System.out.println(((Object) new
in the variable declaration. SuperString()).toString());
The reference type determines which System.out.println(((Object) new
implementation is executed for SubString()).toString("String"));
overloaded methods. System.out.println(((Object) new
The object type determines which SuperString()).toString("String")
implementation is executed for );
overridden methods.
19
17 Given:

12
public interface Shape { public interface StringInterface {
public long getArea(); public String toString();
public int getPerimeter(); }
}
public class Rectangle implements public class SuperString implements
Shape { StringInterface {
//implementation omitted public String toString() {
public int getWidthLength() {return return "Super String";
width;} }
public int getHeightLength() {return }
height;}
public long getArea() {return width class SubString extends SuperString
* height;} {
public int getPerimeter() {return 2 public String toString() {
* (width + height);} return "Sub String";
public double getAngle() {return }
angle1;} public static void main(String[]
} args) {
public class Square extends //insert code here
Rectangle { System.out.println(str);
//implementation omitted }
public int getSideLength() {return }
side;}
} Which three statements, when inserted in the
public class Rhombus extends Square code, will generate the output Super String?
{
Object str = new SubString();
//implementation omitted
public double getAngle1() {return Object str = new SuperString();
angle1;}
public double getAngle2() {return SubString str = new SubString();
angle2;}
public static void main(String[] SuperString str = new
main) { SuperString();
Shape sh = new Rhombus(5,65, 115); StringInterface str = new
Square sq = (Square) sh; SubString();
}
StringInterface str = new
} SuperString();
Which methods are available when using the sq
variable? (Choose all that apply.) 21
getArea Given:

getAngle Writer writer = new Programmer();

getAngle1 Assuming that Programmer is a subclass of


Writer, which statement executes a method
getAngle2 found only in the Programmer class?
getPerimeter writer.write();

getSideLength ((Writer) writer).write();


getWidthLength writer.learnLanguage("Java");

getHeightLength ((Programmer)
writer).learnLanguage("Java");

20
Given:
22
Given:

13
final class OutputSuperClass { Shape {
OutputSuperClass() { //implementation omitted
System.out.println("Super"); public int getWidthLength() {return
} width;}
} public int getHeightLength() {return
height;}
class OutputSubClass extends public long getArea() {return width
OutputSuperClass { * height;}
OutputSubClass () { public int getPerimeter() {return 2
System.out.println("Sub 1"); * (width + height);}
} public double getAngle() {return
OutputSubClass (int x) { angle1;}
System.out.println("Sub 2"); }
} public class Square extends
OutputSubClass (int x, int y) { Rectangle {
System.out.println("Sub 3"); //implementation omitted
} public int getSideLength() {return
public static void main(String[] side;}
args) { }
new OutputSubClass(1); public class Rhombus extends Square
} {
} //implementation omitted
public double getAngle1() {return
What is the result? angle1;}
Sub 2 public double getAngle2() {return
angle2;}
Sub 3 public static void main(String[]
main) {
Super Shape sh = new Rhombus(5,65, 115);
Sub 1 }
Super }
Sub 2
Which methods are available when using the sh
Compilation fails. variable? (Choose all that apply.)
An exception is thrown at run time. getArea

getAngle
23
Which statement is true about interfaces? getAngle1
An interface may contain only public getAngle2
abstract instance methods and class
constants. getPerimeter
An interface can implement methods
getSideLength
defined by other interfaces.
Interfaces support class instantiation like getWidthLength
concrete classes.
getHeightLength
Interfaces do not support overloaded and
overridden methods.
25
24 Given the following code:
Given:
public interface Card {}
public interface Shape { public abstract class PlayingCard
public long getArea(); implements Card {}
public int getPerimeter(); public class PokerCard extends
} PlayingCard {}
public class Rectangle implements public class FlashCard implements
14
Card {} this();
public class NoteCard implements
Card {} super();

public class Game { this.OutputSuperClass();


public static void main(String[]
args) { super.OutputSuperClass();
//insert code here
System.out.println((c instanceof
Card) ? "Card!" : "Not Card?" );
27
System.out.println((c instanceof Which class declaration is valid for a class that
PlayingCard) ? "PlayingCard!" : "Not manipulates String objects?
PlayingCard?" ); public class MutableString
System.out.println((c instanceof extends String
FlashCard) ? "FlashCard!" : "Not public class MutableString
FlashCard?" ); extends StringBuffer
System.out.println((c instanceof
public class MutableString
NoteCard) ? "NoteCard!" : "Not
extends StringBuilder
NoteCard?" );
} public class MutableString
} implements Appendable,
CharSequence
Given the following output:
28
Card!
Which type defines a valid abstract class?
PlayingCard!
Not FlashCard? public abstract class Programmer
Not NoteCard? {
public final Programmer (String
language);
Which statement, when inserted in the code, will
public final void writeCode();
generate the required output?
}
Card c = new PokerCard();
public class Programmer {
NoteCard c = new PlayingCard(); private String language;
public Programmer (String
FlashCard c = new PokerCard(); language);
public void writeCode();
PokerCard c = new PlayingCard(); }
public class Programmer {
26 final abstract Programmer (String
Given: language);
final abstract void writeCode();
public class OutputSuperClass { }
OutputSuperClass() { public abstract class Programmer
System.out.println("Super"); {
} private String language;
} public Programmer (String
language) {
public class OutputSubClass extends this.language = language;
OutputSuperClass { }
OutputSubClass () { public void writeCode() {
//insert code here System.out.println("Written in "
System.out.println("Sub"); + language);
} }
} }

Which statement, when inserted in the code, will


29
generate the output Super?

15
Given:
Which two types use ShiftCipher correctly?
public abstract class Writer { public interface AutoShiftCipher
public void write() implements ShiftCipher {
{System.out.println("Writing...");} public byte[] encrypt(byte[]
} plaintext);
public class Author extends Writer { public byte[] decrypt(byte[]
public void write() ciphertext);
{System.out.println("Writing }
book");}
} public interface AutoShiftCipher
public class Programmer extends extends ShiftCipher {
Writer { public byte[] encrypt(byte[]
public void write() plaintext);
{System.out.println("Writing public byte[] decrypt(byte[]
code");} ciphertext);
public static void main(String[] }
args) { public class TextCaesarCipher
Writer w = new Programmer(); extends ShiftCipher {
w.write(); public String encrypt(String
} plaintext, int shift)
} {/*implementation omitted*/}
public String decrypt(String
What is the result? ciphertext, int shift) {/*
implementation omitted */}
Writing...
}
Writing book abstract class ByteCaesarCipher
extends ShiftCipher {
Writing code public String
encryptAndDecrypt(String txt)
Compilation fails. {/*implementation omitted*/}
An exception is thrown at run time. }
public class ByteCaesarCipher
implements ShiftCipher {
30 public byte[] encrypt(byte[]
Which two statements are true about the this plaintext, int shift)
keyword? {/*implementation omitted*/}
The this keyword can access all public byte[] decrypt(byte[]
superclass constructors. ciphertext, int shift) {/*
implementation omitted */}
The this keyword can access all }
superclass members.
The this keyword can invoke overridden
methods in the same class.
The this keyword can invoke overloaded
methods in the same class.

31
Given:

public abstract class ShiftCipher {


public abstract String
encrypt(String plaintext,int shift);
public abstract String
decrypt(String ciphertext,int
shift);
}

16
8. exceptions public static void main(String[]
args) {
try {
1 readData(Paths.get("test"));
Which two method declarations will compile if } catch (IllegalArgumentException
their implementation code throws an ex) {
UnsupportedOperationException? System.err.println(ex);
void trySomething (OperationType }
op) }
void trySomething (OperationType public static void main(String[]
op) throw ReadOnlyBufferException args) {
void trySomething (OperationType try {
op) throws readData(Paths.get("test"));
UnsupportedOperationException } catch (IOException ex) {
System.err.println(ex);
void trySomething (OperationType }
op) throw }
BadStringOperationException

4
2 Given:
Which statement is true about exceptions?
Exceptions are used to group and public class ExceptionFun {
differentiate error types. public ExceptionFun(Object obj) {
Exceptions are used to handle error if (obj == null)
conditions during normal operation. throw new
IllegalArgumentException("Provide an
Caught exceptions are propagated up the object!");
call stack. System.out.println(obj + "
Unhandled exceptions are propagated created!");
down the call stack. }
public static void createObject() {
try {
3 ExceptionFun obj = new
Given the following method: ExceptionFun(null);
} finally {
public static String readData (Path System.out.println("Was the object
filePath) created?");
throws IOException, }
IllegalArgumentException { }
//implementation omitted public static void main(String[]
} args) {
createObject();
Which two code fragments will compile? }
public static void main(String[] }
args) {
readData(Paths.get("test.txt")); What is the result?
}
ExceptionFun is created!
public static void main(String[]
args) ExceptionFun is created!
throws IllegalArgumentException{ Was the object created?
readData(Paths.get("test.txt")); is created!
}
public static void main(String[] is created!
args) Was the object created?
throws IOException{ Compilation fails.
readData(Paths.get("test.txt"));
} An exception is thrown at run time.

17
op) throws
5 BadStringOperationException
Given:
7
public class ExceptionFun { Given:
public ExceptionFun(Object obj) {
if (obj == null) public String messWithString(String
throw new IOException("Provide an str)
object!"); throws
System.out.println(obj + " StringIndexOutOfBoundsException {
created!"); //implementation omitted
} }
public static void createObject() {
try { Which handling action is required when invoking
ExceptionFun obj = new
the messWithString method for the code to
ExceptionFun(null);
} finally { compile?
System.out.println("Was the object No handling action is required.
created?");
Catch
}
} StringIndexOutOfBoundsException.
public static void main(String[] Specify
args) { StringIndexOutOfBoundsException.
createObject();
Invoke the method within a try block
}
} without an associated catch or finally
block.
What is the result?
ExceptionFun is created! 8
An exception is a(n) ______________.
ExceptionFun is created!
event that affects default flow of the
Was the object created?
runtime.
is created! runtime check during normal runtime
is created! conditions.
Was the object created? list of methods executed by the runtime.
Compilation fails.
handler for abnormal runtime conditions.
An exception is thrown at run time.
9
6 Given:
Which two method declarations will compile if
their implementation code explicitly throws a public class RuntimeExceptionTests {
BadStringOperationException? public static char
performOperation(String str) {
void trySomething (OperationType return str.charAt(0);
op) }
void trySomething (OperationType public static void main (String[]
op) throws Exception args) {
void trySomething (OperationType performOperation(null);
op) throw }
UnsupportedOperationException }
void trySomething (OperationType Which exception is thrown by running the given
op) throw code?
BadStringOperationException
NullPointerException
void trySomething (OperationType

18
IndexOutOfBoundsException
13
ArrayIndexOutOfBoundsException Given:
StringIndexOutOfBoundsException public class ExceptionHandling {
public static void trySomething ()
10 throws FileNotFoundException {
//implementation omitted
Which of the following statements is true about
}
the catch and specify requirement for exceptions?
public static void main (String[]
All Throwable objects must be caught or args) throws IOException {
specified for method code to compile. //insert code here
All Exception objects must be caught or }
specified for method code to compile. }
All RuntimeException objects must be
Which fragment should be inserted in the code for
caught or specified for method code to the program to compile?
compile.
trySomething();
All Exception objects, excluding
RuntimeException objects, must be try {
caught or specified for method code to trySomething();
compile. }
try {
11 trySomething();
} finally {
Which exception indicates that an index is invalid
throw new Exception();
when using a vector, array, or string?
}
RuntimeException
try {
IndexOutOfBoundsException trySomething();
} catch (FileNotFoundException
ArrayIndexOutOfBoundsException ex) {
throw new Exception();
StringIndexOutOfBoundsException }

12 14
Given: Which exception class indicates that a character
public void copy(Path srcFile, Path index is either negative or not less than the length
destFile) { of a string?
try { BadIndexBoundsException
byte[] readBytes =
Files.readAllBytes(srcFile); BadStringOperationException
Files.write(destFile, readBytes);
} catch (______________ e ) { CharIndexOutOfBoundsException
System.err.println(e.toString());
} StringIndexOutOfBoundsException
}
15
Which insertion will allow the code to compile?
Which three exception classes are checked by
Error the compiler?
IOError Throwable

IOException Exception

FileNotFoundException RuntimeException

FileSystemNotFoundException StackOverflowError

19
ClassNotFoundException

ConcurrentModificationException

16
Which statement is true about exception
propagation?
If an exception is thrown in a try block,
the code continues its normal execution.
Whether an exception is thrown or not
thrown in a try block, the code in the
finally block will execute.
If an exception is specified, then that
exception will not be propagated up the
call stack.
If an exception is caught, then that
exception is propagated up the call stack
automatically.

20

Potrebbero piacerti anche