Computer Science Spring Break
Computer Science Spring Break
Practice Exams
7.
Consider this inheritance hierarchy, in which Novel and Textbook are subclasses of Book.
-t0{.w
\7hich of the following is afalse staremenr about the classes shown? J (A) The Textbook class can have private instance variables that arc in neither Book nor Novel. (B) Each of the classes-Book, Nove1, and Textbook-can haye a method cornputeshelflife, whose code in Book and Novel is identical, but differ3 i( ent from the code in Textbook.
./(C)
/-
)P*
''
^'[,'-tr.t
p.i*t" instance variables nyTitle and nyAuthor, then Novel and Textboot< inherit them but cannot directly access them. Both Novel and Textboot inherit the constructors in Book.
U the Book class has
If the
, prrcte*;;E;a;;1t"a.""aiir", this
,p
merhod
may_qolv
lrL
orCLpt-a-i
2.
hprogrammer is designing a program to catalog all books in a library. He plans to have a Book class that stores features of each book: author, title, is0nShelf, and so on, with operations like getAuthor, getTit1e, getShelflnfo, and setShelf fnto. Another class, Librarylist, will store an array of. uook objects. The Librarylist class will include operations such as listAllBooks, addBook, removeBook, and searchForBook. The programmer plans to implement and test the Book class first, before implementing the Librarylist class. The programmer's plan to write the Book class first is an example of -@f top-down development. ((B D bottom-up development, \,4) procedural abstraction. / ' 6),infor^ation hiding I
rt "^^*
r,
.'t'a
'1
*1
/)'uo /
rc,-
t-
t!^-*1*yp
' ) /t
-1rJ,---Y'Ll ,rt)
/r
[, -*i.
l''".-f'^^ir-t'''l
c''
"*'t-.]'c"''tg
't\''!-ra'\'^h-'t '''
i r: tt
.' '' '
.u"*'r'r-tv' ; -i /r L-'1-'i'"tr'"'*-'c'lt rL
',,"
+' u Ai''' i***i "'-"-/ _ i'rii{ I, u-.---/u,1r'- *tt 3__rr_{ r" i, \ (= *'"-f ^-]|, L,*'-"'v-
]';i
"J
'Uv^'l^'
5nj*'
u--,
"
u'.1
l.
I
Questions 3-4 re{erto the card and Deck
classes
FlCEi,rlrV
E-,l,6lIrI>
shown below'
public
cl-ass Card
{
Private String nYSuit; private int nYVaiue;
//O to tz
{ /*
imPlementation
*/ }
public String getSuito { return rnYSuit; } public int getValueo { return roYValue; } public String toStringo
if
(nyValue == 11) faceValue = rrJil ' else if (myValue == 12) faceValue = rrQrr ' else if (nyValue == 0) faceValue = rrKrr ' else if (nyValue == 1) f aceValue = t'Au' if (nyValue >= 2 && mYValue <= 10) return nyValue + rr of r + nySuit; else return faceValue * rr of " + nySuit;
]
public class
Deck
NUMCABDS
= 52;
{ ...
//Simulate sbuffling the deck. public void shuffleo
t...
//ot\er
methods
not
shown
...
3. \(hich
/*
implementation
*/
codeforthecon-
,'@ l*-/
^-!,.^.t*-
\"
o<lL
r-
(C) Card =
p)
Cara = new
Card(suit, value) i
.'
getValueO; X
4.
royDeck, one
per 1lne'
implementation code
*/
)
\7hich of the following is correct
/*
implernentation
cod.e
U-J fu,
;
Println(card)
6"' I
r --{*
III tor
(Card card
System. out
.
nYDeck)
- -ir;"Ii-.fi,> =--1qm";iiiy
(E) II andIII
onlY
Y"
br
I tr--- .L*,
l**l
:&
10
Practiee Exams
5.
Refer to the following method that finds the smallest value in an arr^y.
/,/Precondition: qrr is initlalized with int values //Postcondition: Returns the sroallest value in arr. public static 1nt findMin(int[] arr)
if
"
iudex++;
) return nin;
)
\7hich replacement(s) for
of the f indMin method?
/*
someoalue
*/ willalways
\*-
I-rnteger,
MrN- VALUE,
II III
Integer.MAX-VALUE
arr [0]
(B) II only (C) III only p) I and III only (E) II and III only
],
lvL.t
,",
W*-kLe1
w\ !..fr-'
,^
/"
.,
$r rt
,v# s
kr* 'i
t.
r"'rU
I,,,.
(.o
r\,t,1.\oL.y
L*
t1* rA
#^L-u
{
I
,J
I
l'-t'a*^'"f
11
I
'
t'
)
i++)
] {
public void
secondTestMethodo
SYsten.out.Print(element + u
iucrement (elenent)
');
ffi,wi11beproducedbyinvokingfirstTestMethodforaTe8terobject?
(C)soz (D)ooo
(B) No oritpur will
be thrown. .,
be produced. An Arraylndex0ut0fBoundsExceptlon
will
4, 5?
(C)sez
(D)qoo
be
(7-).t'|
Ll
1\
+CTtt)i
V
// rr.- ( |rl )
An ArraylndexoutofBoundsException will
12
Practice Exams
8.
for(inti=0;i<n;i+=2)
{ )
<-._"'>
fr
l//
In.terms of n, which Java expression represents the maximum number of times that /* perform some action */ could be executed?
9. A method is to be written to search an array for a value that is laiger than a given item and return its index. The problem specification does not indicate what should be returned if there are several such values in the array. \flhich of
the following actions would be best?
a
Ia
The method should be written on the assumption that there is only one value in the array that is larger than the given item. (B) The method should be written so as to return the index of every occurrence of alarger value. The specification should be modified to indicate what should be done if there is more than one index of larger values. p) The method should be written to ourpur a message if more rhan one larger value is found. The method should be written to delete all subsequent larger items after. a suitable index is returned.
(E
13
i.f (x'>
else
y)
C'v#tr*-n
/ i@o"ivwhenr S'y J
(Al Onlywhenx <Y
lF[ if)
lQLOnlYwhenr
)y
x,
a stack
For all values olx andY fn" method will never cause
overfow'
J", f\"ar1. D r htt I i .r,,, :1" ':i i' I 6' :lll .1'.I,r atir > ,.ax ,v4 t5\ r',-'?ur': [3]
^ril p)
true (E) tarse
ll
!(nax !=
a[i])
canbesimplifiedto ,
fxl"**
N t)J
t i N/c''4
{"
a hex' 12. Suppose the characters 0,1,...,8,9,A,8,C,D,E,F are used to rePresent ,a"at"a @ase-16) number. Here A = 10, B = 11, "''F = 1-5' Vhat is the largest i*"-ro irri.g., that can be represented with a two-digit hexadecimal numbe6
such as 14 or 3A?
f"
0 5)
Q)
(E)
2s6
,272
trq)
?vq
i++)
Suppose a list 13. Consider a ctowo class that has a default constructor. wrl]. not cause an Arraylis.t<c1own) list is initialized. \flhich of the following Index0ut0f BoundsExcePtion to be thrown?
list.set(i,
new ClownO)
(B) :.ist . add(Iist . size O , new clowno ) ; (C) Cfown c = Iist.get(list.sizeo) ;' (list ' size O ) ; 1Q) Cf own c = list . renove \J (EXri"t.add(-1, new clownO) ; a-,
\
private Point myTopleft; //coords of top left corner private Point myBotRight; //cooxds of bottom right corner
//constructor public Rectangle(String labeIs, Point topleft, Point botRight)
{ /*
implementationcode
*/ }
shown
*/ }
-.
'
]
T4,
Which statement about the Quadrilateral class isfake? (A) The perimeter and area methods are abstract because there's no suitable .J default code for them. i I (B) The getlabels method is not abstract because any subclasses of { Quadrilateral will have the same code for this method' (C) If rhe Quadrilateral class is used in a Program, it must be used as a suPerclass for at least one other class. fD) No instances of a Quadrilateral object can be created in a program. ,m Anv subclasses of the Quadrilateral classgrzzqprovide implemgntatio{
I I
I
t(/'
.oi"fortheperimeterandareamethods.'\'-, bo u{!l\
represents correct
t5. Which
tor?
I super(1abe1s); II super(Iabe1s, topleft, botRight) ; III super(labels); -, L nyTopleft = toPleft; = botRight; nyBotRight
'
-:
t,
nA
16
16. Refer
Practice Exams
to the Parallelogram and Square classes below.
{
/
) {
{ /*
int areao
public class
/
shown
shown
*,/ }
]
Re
Consider an
/* Precondition: quadlist contains Rectangle, Parallelograln, or * Square objects in an unspecified order. x/ public static void writeAreas (List<Quadrilateral> quadlist)
for (Quadrilateral
{"*\*_a"*
\$) The area of each Quadrilateral in quad.List will be printed. tr\! compile-time error will occur, stating that there is no area method in
abstract class Quadrilateral. (C) A compile-time error will occur, stating that there is no in classes Recta-ngle, Para11e1og1am, of Square.
getlabels method
Practice Exam One / Diagnostic Test 17. Refer to the doSomething method:
17
postcondition
doSonething(List<SoneType>
= 1i.st.get(i);
0u-e-r*L*'
i { v-''-*,\:
\;
\.r
r'-\..e
\ffiich best describ es the postcondition for doSomething? (A) Removes from list the objects indexed ar i and j. (B) Replaces in rist the object indexed at i with the object indexed (C) Replaces in list the object indexed at j wirh the object indexed (D) Replaces in list the objects indexed at i and 5 with tenp.
at 5. at i.
tre) \_-.,'
Interchanges in
list
and
j.
18. Consider the NegativeReal class below, which defines a negative real number
object.
private
Double nyNegReal
//constructor. Creates a NegativeReal object //Precondition: num ( 0. public NegativeReal (double num) { /* implementation not shown x,/ }
whose
value is
nr:m.
//Postcondition: Returns the value of this NegativeReal. public double getvalueo { /* implementation not shown */ }
//Postcotdition: Returns this NegativeReal rounded to the nearest integer. public int getRoundedo { /* implementation */ }
number
-4 -9 -5 -2
0
*/ of getRounded produces the desired postcondition? (int) (getValueO - 0.5); e. q *3,5 *,5 r eturn I return (int) (getValueo + 0.5); di ]Ql r"trrrn (int) getValueO; t,
implernentation
/*
oZ
', ! ;
& , E L-*r'"O
-.OJ
.-r e
t*"rlr-
(.4pub1 e)'
'(etvatrue C)'-:o'5 ) ;
;
";t
18
19. Consider the following method.
Practice Exams
\
1\ !
,1
r t -",
i,r.r9 '
",t
r/V
Il-.t
i
r ^
'l
' {
I
n)
. r'J "t
if(n>10)
11!
E:
tii
]
(A) (B) (C) @)
i r. '"3''
zs+
243
.'J
,
,t-r\
\. ./
l:
tt*r'
d
Y,
@) (E)
The number of. data movements in selection sort depends on the initial arrangement of elements. The number of da:,z movements in insertion sort is independent of the initial arrangement of elements.
S., C( c-l
$-'b -'
r.1
t'*-u--
,r!rrr*r-V-"
fr{
dau
Utrvr,UJf fli'i:..,$
iI
! f^.-r+^.-t #
-L
.u{/
.*.,.v."{,".ry^
19
and ClassTvo below.
public class
Class0ne nethodOneo
public void
)
:
l: :l i, l'
H
!,
showa
,{
)
//otber nethods aot
shown
ir
cause an error?
IIIc2.nethod0neO.J)
(A) None (B) I only (C) tr only
*M *ulAd
\ i q
L
.l
s l^e+ f
u J,^**
o.<-!t
h^-[.{^-!
Q) Itr onlY
ry
Iandtronly
20
22. Consider the code segment
,
if (n == 1)
else 1f (n == 4)
k++;
Practice Exams
1+=4;
r(
t{
tp*e""-*^* is I f \ctl
^T,LT i+s r"*t
,l
t't-
form
if U* cond.ition */)
/*
dssignment stdternent
\9
{iF
ry
*/
HJ
\\ \
Given that n and k are integers and that the rewritten code performs the same task as the original code, which of the following could be used as and (1) /* condition */ @ /* assignmentstdte.ment */?
lyafn==1&&n==4
! o j'tts
Pi
v =I
O\..)'
@ k+=n @ k*=4
@) 1+=4 I @ k+=n
)
0,^fL sW
(E) (0 n==1lln==4
@) I
k=n-k
IStrings=nulI{ String t X if
stem.
out.println("empty strings?'r
l"
A.
String s = ttholy"; String t = "mo1y"; if (s.equals(t)) Systen. out.println( "ho1y noly ! ") ;
(c)
p)
! I
l; l,
&h
rlr rrl!!l[!rrr!!r
r![!t
I llllllllll
I ll
21
24- Three numbers a, b, and c are said to be a Pythagorean Triple if and only if the sum of the squares of two of the numbers equals the square of the third. A programmer writes a method isPythrriple to test if its three parameters form a Pythagorean Triple: .//Returns true if a * a + b * b == c * c; otherwise returns fa1se. public static boolean isPythTriple(double a, double b, double c)
* a + b * b);
]
\flhen the method was tested with known Pythagorean Triples, isPythTriple sometimes erroneoirsly returned f a1se. 'What was the most likely cause of the
e4aor?
Li'{i''t '
($
Rolrrrd-off error was caused by qalculaii"ons with floating-point numbers. . \ I .i fBtr Type boolean was not recognizedSy an obsolete version of Java. ''jL.\ {e} An overf.ow error was caused by entering numbers that were too large. | '-Lt"*'\' Qf and a should have been cast to integers before testing for equality.
.t
!
{
nystery method.
//Constrlctor. fnj.tializes arr to contain nonnegative // integers k such that 0 (= k (= 9. public SoneClassO r,. { /* inptementation not shown */ }
public int mysteryo { int value = arr[0] i for (int i = 1; i ( arr.length; i++) value = value * 10 + arr [i] ; return value;
1i a'\
f
2,.-'
\
,.1 tt F l'L.'
\ -l
)
\fh,."h best describes what the mystery method does? ,8K) Itsums the elements of arr. .,' g$-ysums the products 10*arr [0] * 10*arr t1l +. . .$ lOxarr [arr.length-1J arr [0] , .;1C). 'u-.'- ,ft builds an integer of the form d1drd, . . . do, where d., = 6r= arr [1] , . . . , do = arr [arr. length-11 . (D) k builds an integer of the form d,rd.rfi . . . do, where urr[arr. length-7f , dz= arr [arr. length-2], ..., dn =arr [0]. ,d.1 = (W k converts the elements of arr to base-1O.
'l-l
::
22
Practice Exams
in the Searcher class below. Questions 26 and27 refer to the search method
*/ }
/* Precondition: arr[first] . ..arr[1ast] sorted i-n ascending order. * Postcondition: Returns index of key in arr. If key not in arr, returns -7. */ i< public int search(int first, int last, int key) { int nid; while (first <= last) { nid= (first +last) / 2; //fourrd key, exit search if (arr[mid] == key)
I i\
,n{i
,j
t-
\{
I"
i ,''-
*-t
t
return mid; else if 1aa1[ni-dJ < key) / /key to right of arr [mid] = mid + 1; //key to left of arr[mid]
L-. \TY
J
\o
1'
i*,';
\
,i
,.i
l/-.
1;
/
i.-.141
I
)
,.--."-.return
)"0
ii-
b
.'L
],.
--'u**.__.:
26.
I ,'o-* -.-
,.t-
Ll
+
r* '1i +l
U.
(
arr[first] ( key ( arr[last] ) arr[first] ( key 1! arr[last] '(C) .rr[tirst] ( key < arr[last] orkeyisnotinarr (7D^rr[f irst] ( key ( arr [last] _or key is not in arr fn; t"y I arrffirst] orkey ) arrllast] orkeyisnotinarr
Conside
\rhi
I!^G-d"+{ lr
iltv
27.
the array
4,
7,
l,
306,321,
^I";J#rcj
where 4 is
aiOl and32lis a[13]. Suppose thkd. search method is called with f irst = 0 and last - 13 to locate the key 205. How many iterations of the wt ite
loop must be made in order to locate
\bfr:.-(c)s
(D)
(A)
':
10
-,
'i:)
class.
{ nytist = getlisto; }
Read random
/*
int l-istlength = I0.readIntO; //read user input iat[] list = int[listlengthJ; for (int i = 0; i < listlength; i++) { /* codctoidd i*eger to Lj..st */ ) return 1ist.
list. */
i*eger fo list */? = (int) (Math.randonO r 101); Srt".[i] (Math.rardonO * 101)); \7rp \rr"..add((int) (C) rist[i] = (int) (]Iath.randonO * tO0);
codc to
/*
add
4--
24
Practice Exams
6il*U* to method insert described here. The insert method has two string paV r"*.r.rs and one integer parameter. The method returns the string obtained by
inserting the second string into the first starting at the position indicated by the integer parameter pos. For example, if strl contains xy and str2 contains cat, then o
insert(strl, str2, 0) returns catxy S,*,)<)nY>' I insert(str1, str2, 1) .;eturns xcaty insert(str7, str2, 2) tatarrrt xycat \-u ?-
sLh
,rLk
sL
/,/Precondition: 0 <= Pos (= strl .IengthO. //Postcondition: If strl =dortt...tn-l and str2 =
returns dod|., . apor-tbob t.
bsbl
...b*-t,
+ 1.
..
. . b *-11prs1pos
dn-7
pos)
/*
morecodc
*/
o( c^*
^)
/*
rnore code
*/?
(B)
vo* *1
first last (c) first last @) flrst last (E) first last
as
int[] []
mat = new
inti2l [3];
for (int r = .0; r < mat.length; r++) for (int c = 0; c < mat[r].length; c++) if (r == 61 nat[r] [cJ = Y"t1.abs(nat[r] [c]);
If nat is initialized to be
-2-4
-7 -2 -6
5
a call
to chaageMatrix(mat)
@) t2-6 24 5
{Efizo s '\J2 4
.t I
nl
\-"'
lo*t
kl,
\/(,..s,.,t
C^-*8.
ru,{,f.+
hn
f'tl't'r'Y
e"('r{
:.
o{vPj")''
\*,
i-V'\
i
$
tl:
c irt i,tr
*i
;26
Use the following program description for euesrions 31-33.
Practice Exams
. '
A Programmer plans to write a program that simulates a small bingo game (no more than six players). Each player *iit t a_ bingo card with 20 numbers fr"om o to 90 (no ":* duplicates). Someone will call out numberr"o.r. ,, a time, and each player will cross out a number on his card as it is called. The first player with all th" ,.r-b"rs crossed out is the winner. In the simulation, ,r the gr*" i, in progr.ss, each player,s card is
The programmer envisions a short driver class whose naj.n merhod has just two
BingoGa_meO;
b = new b.playBingoO;
BingoGame . \ . ?t
t
\,".\f\--'
',!,ar' .{'
\i
; "'
$,f
\.i
{,1
I
i;.'.Leri
t- I t {:t
31''The relationship between the PlayerGroup and player classes is an ' example of WI FI t 1 | ty* -- (B) encapsulation. '1' --('{)*an-interface,'* . c/' (e ,- (9) comp<i-sffionr..,' ,t' t t 6 !\ -6w\i lr,r Lfi.r,u.L, n, , -.,1 ! '(Di inheiitance. !i:r.13tr i\"rio', ' ',i'lrl ir A-
The BingoGame class will have several objects: a Display, a ca11er, and a playerGroup. The PlaverGroup will have a list of etayers, and !4eu er"y". will vro' @,u erch rrdyer wur have a Bingocard. lave t
. {:'" I i ,.. ol .l
lt1.'r'.'.f,.,(
,11
,.r'./
32. \flhich is a reasonab le datastructure for a Bingocara objelt? Recall rhar there are 20 integers from 0 to 90 on a Bingocard, with no duplicates. There should also be mechanisms forcrossing off numbers that are cailei, and for detecting a winning ard (i.e., one where all the numbers have been crossed off).
I int[] int
numcro"
II boolean[J
""I(lf
//wiltcontain 91 boolean values, of which //20 are true. A11 the other values are false. //Thus, if myBingoCard[k] is true, then k is //on the card, 0 <= k <= gO. A number k is /,/crossed off by changing the value of / /myBingoCard [k] to f a1se. i-nt numCrossed0ff; //player wins when numCrossed0ff reaches 20.
myBingoCard.;
III Arraylist<Integer> nyBingoCard; //wl]]]= contain 20 i.ntegers. //A mr:aber is crossed off by removing it from the Arraylist.
//Player wins
when myBingoCard,sizeO ==
O.
(A) I only (B) II only (C) III only (D) I and II only (E) I, II; and III
^c(
l'-tulc r ,i
,.r
:'-.j4
27
as an
33. The programmer decides to use a List<rnteger>, which is implemented Arraylist<rnteger), to store the numbers to be called by the ca1ler:
private List<Integer)
//constructor public Callero
nyNumbers
{
myNumbers
= getlistO;
shuffleNumbers O ;
//Return the numbers 0...90 iu order. private List<fnteger> getlist o { /* impleroentation not shor,m ,r,/ }
Te{
f, private List<fnteger> myNumbers = nu11; {\ \P) Y" the getlist method, an aftempr was made ro add an Integer vArraylist thar had not been created with new.
Jn{
The shuffleNumbers algorithm went out ro be shuffled into the Arraylist.
ro
an
of
range,causing
anu1l rnteger
{ a.}
B,-\I"u
@ ,,rr',{.iu'. ;*-*.'.a+ ifv,*..'u *"1 ,lkl**ilr. -P>h*$. ,,r'l ..,*5 i d l, i.,-,Jt ,lo*{r}^ i ^}L.{f*f' v...f " q,*vL,kc r-qhJL,d* l"**i tri -,^[ ilJr, iv.J h.!/!-,4 p
// *-*r-f"v^e-,Lu-r
P,J,K,;
bw[U
'
W nd'L-*jUJ'''(''^*f i"J'Ct
'i+ W *^t:fHt
S-4rarl * n-;
t
'ffi7
-.
l..or-.,Lt *tt =
ri,...L(,"[,r.*
Fn q
,
I
-t*\
"*,-"{'"
ro-** J
: I\^a J; *\yt
r.Jt t
\
0
t ^J^1"'c t*
S{-,.S\.
r*}
i.
(W*lr*
")t
,^^h,!t,
t*J<
r*Lft ^ *5 . -/J ".4.r^ n u*JAt* I,* k I ;?. W, p,rJ4!"', st-^,f..' e v o ; J re.+v+ g"".-h (W,J.,l O5 1 ,il-nL tr,*tr /) I 2o eJ S. (*Jlc*( r r). f+L
hu.^tV
,^j
'
st ,y(
r,
\44b
9.
peraa..er,rs Ce,
frJPA
Cr)\.
,f @, p*l&'. th/+, t//*ol t,r* ohy.,t"*rytPo"^A (tfi-,&.t) W,*rXs..t z): W e-le" V = \L+w W*&*c>; fu*'. (r** "" ij i a= *.? $" -, j +|.) : ,. :t, ,,
9
fr.:
t,.04+-
Wvol= !1,
A-rl k*t0 \i
,t
I
vchrr
4:
6) oi
J4J
[,
-/-u-**.1., {'l
...i
z
{
V\r^-.i
( *"/
L-
i5 k
, <-.1n,
(Dy, ^l"f^ t
t
o--J,,l
ff!*V*l\rr**-, ,
i.*t ,*f
i
,d i1,,,."**,it*L"an",
or*-r,L\ {r, o) q
,
OJrI
a)*|sy'l*]
t4/,\,1
g
{
UtJ
F
tl
ul,
)'
rz^.,4-a^-'rcr,'t-4
y't 'l*v i
I'
t*FE
t 'J-i