You are on page 1of 24

6

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

Boot< class has

, prrcte*;;E;a;;1t"a.""aiir", this
,p

be accessed in either tlie Novet or Textbooli classes.

nu-tk i-*l-t"'[* r1,. -*4

merhod

may_qolv

lrL

orCLpt-a-i

GO ON TO THE NEXT PAGE.


lua;.,

Practice Exam One / Diagnostic Test

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

1yf ^driver program.

/-! \, fr o"(L +\l

rt "^^*

r,

.'t'a
'1

*1

z'rt'* 't;; * w-"


(

/)'uo /

rc,-

t-

t!^-*1*yp
' ) /t

tv'-r '['\'-ti ; 'vt

-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.

GO ON TO THE NEXT PAGE.


b,$

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

public Card(String suit' int value)

{ /*

imPlementation

*/ }

public String getSuito { return rnYSuit; } public int getValueo { return roYValue; } public String toStringo

String faceValue = "";

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

private Card[] nyDeck; public fi.nal static int


public Decko

NUMCABDS

= 52;

{ ...
//Simulate sbuffling the deck. public void shuffleo

t...

//ot\er

methods

not

shown

...

GO ON TO THE NEXT PAGE.

Practice Exam One / Diagnostic Test

3. \(hich

of the following represents correct


class?

/*

implementation

*/

codeforthecon-

structor in the Cara

,'@ l*-/

rnySuit = suit; nyValue = value;

^-!,.^.t*-

(B) suit = nySuit;


value =
rnyValue;

\"

o<lL
r-

(C) Card =

new Card(nySuit, nyValue);

p)

Cara = new

Card(suit, value) i
.'

(E) nysuit = getSuitO.! '


nyValus =

getValueO; X

4.

added to the Deck Consider the implementation of a writeDect< method that is


class.

public void. writeDecko

//Urite the cards in {


/

royDeck, one

per 1lne'

implementation code

*/

)
\7hich of the following is correct

/*

implernentation

cod.e

I System. out .Printla(mYDeck) ; II for (Card card : mYDeck)


System. out
.

U-J fu,
;

Println(card)

6"' I

r --{*

III tor

(Card card
System. out
.

println( (String) card

nYDeck)

- -ir;"Ii-.fi,> =--1qm";iiiy
(E) II andIII
onlY

(r\) tr enlv '

Y"

br

I tr--- .L*,

l**l

Yi, 1i!' Sir.

:&

GO ON TO THE NEXT PAGE.

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)

int min = /* someaalue */; int index = 0; while' (index ( arr.length)


r(

if

(arr [index] < rnin) min = arr[index];

"

iudex++;

) return nin;

)
\7hich replacement(s) for
of the f indMin method?

/*

someoalue

*/ willalways

result in correct execurion

\*-

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

t\r\r4 t^ l,r -r'v\-%v. -r t/\{

],

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

GO ON TO THE NEXT PAGE,

Piactice Exam One / DiagnosticTest


,

11

Refer to the followirrg class for Questions 6 and 7.

public class Tester

private int[] testArray = {3, 4, 5};

//ua 1 to n. pubIlc void increment (int n) {


n++';

I
'

public void firstTestMethbdO '

for (int i = 0; i < testArray.length;

t'
)

i++)

Systen.out.priat(testArray[i] + " ") ;

increnent (testArray [iJ ) ;

] {

public void

secondTestMethodo

for (int elenent : testArraY)

SYsten.out.Print(element + u

iucrement (elenent)

');

ffi,wi11beproducedbyinvokingfirstTestMethodforaTe8terobject?

(C)soz (D)ooo
(B) No oritpur will
be thrown. .,

be produced. An Arraylndex0ut0fBoundsExceptlon

will

7. Vhat outpur will

be produced by invoking secondTestMethod for a Tester ob3


,

ject, aszuming t"hat testArray contains

4, 5?

(C)sez
(D)qoo
be

(7-).t'|
Ll

1\

+CTtt)i
V

// rr.- ( |rl )

inl N" ourput will be produced.


throvrn.

An ArraylndexoutofBoundsException will

GO ON TO THE NEXT PAGE.

12

Practice Exams

8.

Consider the following loop, where n is some positive integer.

for(inti=0;i<n;i+=2)
{ )
<-._"'>

if (/* test */) /* perform some action */

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

GO ON TO THE NEXT PAGE.

Practice Exam One / Diagnostic Tbst


mem10. \flhen will method whatlslt cause a stach overfow (i.e., cause comPuter ory to be exhausted)l

13

public static iat whatfslt(iut x, int y)

i.f (x'>
else

return x * yi return whatfslt(x - 1, Y);


YA

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'

11. Thebooleanexpressiona[i] == nax == @'1

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?

{A) tor (int i = 0; i (= Iist'sizeo;

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-,
\

GO ON TO THE NEXT PAGE.

Practice Exam One / Diagnostic Test

public class Rectangle extends Quadrilateral

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

*/ }

public int Periroetero { /* inplementation not public int areao //other


methods

shown

*/ }

{ /* inplementation not shown */ }


not
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?

/* implementation cod'e */ for the Rectangle construc-

.,, 6vf,'w!- r :.,A1\

I super(1abe1s); II super(Iabe1s, topleft, botRight) ; III super(labels); -, L nyTopleft = toPleft; = botRight; nyBotRight
'

-:

t,

(A) I only (B) II onlv


:ntonty (D) I and II only (E) II and III onlY

nA

16
16. Refer

Practice Exams
to the Parallelogram and Square classes below.

public class Parallelogran extends Quadrilateral

{
/

/priv.ate instaace varlables . end constructor not'Shown

public 1nt peri.netero { /*, inplementati.on not shown */ }


pub11c

) {

{ /*

implementation not shown *,/


Square extends Rectangle

int areao

public class
/

/private instance variables and constructor not

shown

public int perimetero { /* inplenentation uot public int areao

shown

*,/ }

]
Re

{ /* inplementation not shown x/ }


Arraylist<Quadrilateral> quad.List whose elements
are of type

Consider an

ctangle, Parallelogram, or Square. Refer to the following method, writeAreas:

/* Precondition: quadlist contains Rectangle, Parallelograln, or * Square objects in an unspecified order. x/ public static void writeAreas (List<Quadrilateral> quadlist)

for (Quadrilateral

: quadlist) System.out.println("Area of " * quad.getlabelso * 'r is il + quag..areaO) i


quad ..: ,r r,_i,i y v'./. l ;A ltt\..l l;
u

{"*\*_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.

l$Kfuat is the effect of executing this meth6d?

getlabels method

(D) A NullPointerExceptionwill be thrown. (E) A ClassCastException will be thrown.

GO ON TO THE NEXT PAGE,

Practice Exam One / Diagnostic Test 17. Refer to the doSomething method:

17

public static void

postcondition

doSonething(List<SoneType>

{ list . set (i, list . get (j ) ) ; list. set (j , tenp) ;


SomeType temp

Iist, int i, int j)

= 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

the objects indexed at

and

j.

18. Consider the NegativeReal class below, which defines a negative real number
object.

public class NegativeReal

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 */ }

Here are some rounding examples:


Negative real

number

Rounded to nearest integer

-3.5 -8.97 -5.0 -2.487 -0.2

-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 ) ;
;

(E) return (doulrH-gaflfelueO

fdYU v rJL, L ',1

";t

GO ON TO THE NEXT PAGE.

18
19. Consider the following method.

Practice Exams

\
1\ !
,1

r t -",

i,r.r9 '
",t

r/V

Il-.t
i

r ^
'l

' {
I

public static void whatslt(int


whatslt (n / 70); System.out.print(n % 10)
as a

n)

l-..{' I U'. _! ,P' \.-'\".

. r'J "t

if(n>10)

11!

E:

tii

]
(A) (B) (C) @)

\7hat will be output


z+ +z

resuk of the method call whatslt (347)?

i r. '"3''

zs+
243

.'J
,

,t-r\
\. ./
l:

tt*r'

d
Y,

20. Alargelistof numbersistobesortedintoascendingorder. Assumingthata"data


movement" is a swap or reassignmenr of an elemenr, which of the following is a true statement? (A) If the array is initially sorted in descending order, then insertion sort will -_-----.,b" more efficient than selection sort. {@ylhe number of comparisons for selection sorr is independent of the initial arrangement of elements. (C) The number of comparisons for insertion sort is independent of the initial
arrangement of elements.

@) (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^

GO ON TO THE NEXT PAGE.

Practice Exam One / Diagnostic Test

19
and ClassTvo below.

21. Refer to the definitions of classone

public class

Class0ne nethodOneo

public void

)
:

l: :l i, l'
H

!,

//other nethods not

showa

publ-ic class ClassTwo extends Class0ne

,{

publ1c void methodTwoo

)
//otber nethods aot
shown

Consider the following declarations

ir

a client class. You may assume that

Class0ne and ClassTwo have default constructors.

cl = new CLass0neo; Class0ne c2 = new Cl-assTwoO i


C1ass0ne

!(lhich of the following method calls will

cause an error?

IIIc2.nethod0neO.J)
(A) None (B) I only (C) tr only

h, I Vl" IIc2.nethodTwoO; nn. Uf ,


Icl.nethodrroO;-

*M *ulAd
\ i q

L
.l

s l^e+ f

u J,^**
o.<-!t

h^-[.{^-!

Q) Itr onlY

ry

Iandtronly

GO oN TO THE NEXT PAGE]

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-

Suppose that the given segment is rewritten in the

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

23. \7hich of the following will execute withoat throwing an excePtion?

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 ! ") ;

Itr Strlng s = "hoLy"; String t = s.substring(4); Systen. out.println(s + t) ;


(A) I only

(c)

p)

I and tr only (E) tr and III only

! I

GO ON TO THE NEXT PAGE.

l; l,

&h

rlr rrl!!l[!rrr!!r

r![!t

I llllllllll

I ll

Practice Exam One / Diagnostic Test

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)

double d = Math.sqrt(a return d == 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.

" (E) Bad test data were selected.

.t

!
{

25. Refer to the following

class, containing the

nystery method.

publi-c class SomeClass

private int[] arr;

//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.

GO ON TO THE NEXT PAGE.

'l-l

::

22

Practice Exams
in the Searcher class below. Questions 26 and27 refer to the search method

pubU-c class Searcher

private int[] arr;


//Constructor. fnltializes arr with integers
publi-c Searchero { /* implementation not shown

*/ }

/* 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/-.

"r""tt'"t = nid last


-1;

1;
/

i.-.141
I

)
,.--."-.return

)"0
ii-

r ,t i ,+-\. .' ! ,"! Vr.'.f i:


I

b
.'L

/key r,ot in l-ist

],.

--'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

'assertion is true just before each execution of the while loop?

I!^G-d"+{ lr

iltv

27.

the array
4,

with values as shown:


27

7,

19, .25,.36,37,50, 1OO, tOt,qZZO,

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)

,'."7, *i:-Ii: *q.'" '\'r')'"1 4 t?,-?. L:


s r )'ti:,
r

it? ".! - i, F---O -:-"r

':

10

-,

'i:)

GO ON TO THE NEXT PAGE.

Practice Exam One / Diagnostic Test

28. Consider the following Raadonlist

class.

public class Randonlist

private int[J nylist;


//constructor public Raadoml,isto

{ nytist = getlisto; }
Read random

public int[J getlisto

/*

rntegers fron 0 to 100 inclusive into array rist. r./


;

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.

Systen. out.println(,'Hou ma:ry integers?,t)

/* Print al]. elenents of this public void printlisto { ...


\7hich represents correct

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

\fist.add.(new Integer(Uath.randomo,r 100) ) (E) rist[i] = (i.nt) (Math.raadonO * 1OO) + 1;

4--

\",-*! o'ry ^d.J

GO ON TO THE NEXT PAGE.

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

Method insert follows:

/,/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

public static String insert(String str1, String str2, int

pos)

String first, last; return first + str2 + last;

/*

morecodc

*/

o( c^*
^)

\7hich of the following is a correct replacement for

/*

rnore code

*/?

strl.substring{O, @rrr", ==str1. substring(p8s) PP"); - last


;

(B)

vo* *1

first last (c) first last @) flrst last (E) first last

= strl.substring(0, pos - 1); = strl.substring(pos) ; = strl.substring(0, pos + 1); = str1. substring(pos + 1) ;


= strl.substring(0, pos); = strl.substring(pos + 1, strl.lengthO); = strl.substring(0, pos); = strl.substring(pos, strl.lengtnO + 1);

GO ON TO THE NEXT PAGE.

Practice Exam One / Diagnostic Test

30. A matrix (two-dimensional array) is declared

as

int[] []

mat = new

inti2l [3];

Consider the following method:

public static void cha-ugeMatrix(intU [] nat)

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

which matrix will be the result of

to chaageMatrix(mat)

(A) t -2 -6 -245 (B) -r 2 -6 2-4 5 (C) -r -2 -6


-2 -4 -5

@) t2-6 24 5

{Efizo s '\J2 4

.t I

nl

\-"'

lo*t

q*"Q t-,J '*{


I

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

GO ON TO THE NEXT PAGE.

;26
Use the following program description for euesrions 31-33.

Practice Exams

. '

displayed on the screen. statements:

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

l: t t l: .,. t i(t { tr t ll il'


i

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-

./i : , -,, ("[., ,

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

myBingoCard; //wll-i. contain 20 integers

numcro"

II boolean[J

""I(lf

'"Ti;i:J:l ;i":,ff r."fr:,:I"ffi }i"i"ll,l3 ;l

//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

GO ON TO THE NEXT PAGE.

:'-.j4

Practice Exam One / Diagnostic Test

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:

public class Caller

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,/ }

//Shuffle the numbers. private void shuffleNumbers o { /* inplementation uot shown */ }


\7hen the programmer rests rhe consrructor of the caller class she gers a NullPoi.nterException. \7hich could be the cause of this error? (A) The catter object in the driver class was not creared with new. \Q) fl" programmer forgot the return srarement in getlist that returns the

Te{

list of rntegers. The declaration of nyNr:nbers is incorrect. It needed to be

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

GO ON TO THE NEXT PAGE.


.;:..,.ii

itr /*\ \*_.'


\-/

{ 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

c vr-i,t o**,"1, rf*i,"J,l-{.f..,*. {".*J f ffi-1? (" ]


rxap*J!r"*h'*r*iar*t

: I\^a J; *\yt

r.Jt t
\

da^..i,fu yll , t,P Pni*C) 2 i, tlv, r^ *-U, fl^ q @+ r*L*(0r"A'r(W,


./

0
t ^J^1"'c t*
S{-,.S\.

,o,,Jh t^rr^Wo rL A ,oJ

r*}
i.

(W*lr*

")t

,^^h,!t,

t*J<

,,$J L#(c*"bd' Jt;#,til,I'*' "TL)


In "A('n{)

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

W*f i$*'rh ( ''u*t- U'AJj

,t
I

vchrr

4:

6) oi

J4J
[,

-/-u-**.1., {'l

...i

z
{
V\r^-.i

( *"/

L-

i5 k

, <-.1n,

(Dy, ^l"f^ t
t

,,-^$ ^l Pfuy^ ce\-1,\,*L/"t "r/ #'*-*"1,*S l,'{ i{ /-p^ f);


u

o--J,,l

ff!*V*l\rr**-, ,

i.*t ,*f
i

'N PA.*v* N*,*.Ld())


=r,r,-,,
L'i

,d i1,,,."**,it*L"an",

or*-r,L\ {r, o) q
,
OJrI

a)*|sy'l*]
t4/,\,1

g
{

UtJ
F

tl

ffLf, (,^;k-yr, r(, f,

ul,

)'

rz^.,4-a^-'rcr,'t-4

y't 'l*v i

I'

t*FE

t 'J-i

You might also like