Computer Science Spring Break

Embed Size (px)

Citation preview

  • 8/2/2019 Computer Science Spring Break

    1/24

    6

    Consider this inheritance hierarchy,of Book.

    Practice Examsin which Novel and Textbook are subclasses.

    -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 neitherBook nor Novel.(B) Each of the classes-Book, Nove1, and Textbook-can haye a method3 i( cornputeshelflife, whose code in Book and Novel is identical, but differ-ent from the code in Textbook../(C) U the Book class has p.i*t" instance variables nyTitle and nyAuthor, then/- )P* '' ^'[,'-tr.t Novel and Textboot< inherit them but cannot directly access them.Both Novel and Textboot inherit the constructors in Book.If the Boot< class has , prrcte*;;E;a;;1t"a.""aiir", this merhod may_qolvbe accessed in either tlie Novet or Textbooli classes. ,p nu-tki-*l-t"'[* r1,. -*4lrL orCLpt-a-i W V

    GO ON TO THE NEXT PAGE.

  • 8/2/2019 Computer Science Spring Break

    2/24

    Practice Exam One / Diagnostic Test2. hprogrammer is designing a program to catalog all books in a library. He plansto have a Book class that stores features of each book: author, title, is0nShelf,and so on, with operations like getAuthor, getTit1e, getShelflnfo, andsetShelf 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 testthe Book class first, before implementing the Librarylist class. The program-mer'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 I1yf ^driver program. II /-!

    \,fr o"(L +- P *1 ( z'rt'*\l r, , .' 't;; * /)'uo / rc,- t-rt "^^* '1 t'a w-" { u

    t!^-*1*yp tv'-r '['\'-ti ; 'vt .u"*'r'r-tv' ; ',," -i' ) /t 't\''!-ra'\'^h-'t ''' i t /r L-'1-'i'"tr'"'*-'c'lt-1rJ,---Y'Ll l''".-f'^^ir-t'''l t r: rL,rt)/r [, -*i. ]';i 'Uv^'l^' c'' "*'t-.]'c"''tg .' '' '

    t "J{ , u-.---/u,1r'-

    +' u 3 Ai''' i***ii'rii I "'-"-/ _ __rr_{i, ^-]|, \ (= *'"-f *tt r"5nj*' . u--,l. " u'.1 L,*'-"'v-GO ON TO THE NEXT PAGE.

  • 8/2/2019 Computer Science Spring Break

    3/24

    , -, ,IQuestions 3-4 re{erto the card and Deck classes 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 toStringot 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 && mYValuereturn nyValue + rr of relse return faceValue * rr of

  • 8/2/2019 Computer Science Spring Break

    4/24

    u ^-!,.^.t*- /\" o

  • 8/2/2019 Computer Science Spring Break

    5/24

    10 Practiee Exams5. 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 /* someoalue */ willalways result in correct execurionof the f indMin method?\*- I-rnteger, MrN- VALUE,II Integer.MAX-VALUEIII arr [0](B) II only(C) III onlyp) I and III only(E) II and III only

    t\r\r4 t^ ],., l,r, -r'v\-%v. -r t/\{I,^ /"W*-kLe1 ! t. r"'r- I,,,. (.ow\ !..fr-' r\,t,1.\oL.y s L *

    U

    $r rtt1* ,JrA I#^L-u{I{

    I,v# kr* 'ilvL.t ,",s l'-t'a*^'"f

    GO ON TO THE NEXT PAGE,

  • 8/2/2019 Computer Science Spring Break

    6/24

    Piactice Exam One / DiagnosticTest,

    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++'; Ipublic void firstTestMethbdO ' 't for (int i = 0; i < testArray.length; i++)t' increnent (testArray [iJ ) ;Systen.out.priat(testArray[i] + " ") ;)]public void secondTestMethodo{ for (int elenent : testArraY)t iucrement (elenent) ;SYsten.out.Print(element + u ');)))

    ffi,wi11beproducedbyinvokingfirstTestMethodforaTe8terobject?(C)soz(D)ooo(B) No oritpur will be produced. An Arraylndex0ut0fBoundsExceptlon will. , be thrown.

    7. Vhat outpur will be produced by invoking secondTestMethod for a Tester ob-ject, aszuming t"hat testArray contains 3 , 4, 5?

    11

    (7-).t'| 1\ +CTtt)i // rr.- ( |rl )(D)qoo Ll b Vinl N" ourput will be produced. An ArraylndexoutofBoundsException willbe throvrn.(C)sez

    GO ON TO THE NEXT PAGE.

  • 8/2/2019 Computer Science Spring Break

    7/24

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

    for(inti=0;i

  • 8/2/2019 Computer Science Spring Break

    8/24

    Practice Exam One / Diagnostic Tbst 13

    10. \flhen will method whatlslt cause a stach overfow (i.e., cause comPuter mem-ory to be exhausted)lpublic static iat whatfslt(iut x, int y)t

    i.f (x'> y)return x * yielsereturn whatfslt(x - 1, Y);

    11. Thebooleanexpressiona[i] == nax ll !(nax != a[i]) canbesimplifiedto ,@'1 ^ril == J", f\"ar1. D r htt I i .r,,, :1" ':i i' I -[3] :lll .1'.I,r atir > ,.ax ,v4 t5\ r',-'?ur': 6'

    ](Al Onlywhenx

  • 8/2/2019 Computer Science Spring Break

    9/24

    Practice Exam One / Diagnostic Testpublic class Rectangle extends Quadrilateral{

    private Point myTopleft; //coords of top left cornerprivate Point myBotRight; //cooxds of bottom right corner//constructorpublic Rectangle(String labeIs, Point topleft, Point botRight){ /* implementationcode */ }public int Periroetero{ /* inplementation not shown */ }public int areao{ /* inplementation not shown */ }//other methods not shown -. ']

    Which statement about the Quadrilateral class isfake?(A) The perimeter and area methods are abstract because there's no suitabledefault code for them.(B) The getlabels method is not abstract because any subclasses ofQuadrilateral will have the same code for this method'(C) If rhe Quadrilateral class is used in a Program, it must be used as a suPer-class for at least one other class.

    T4,II.JIiI{

    t5.

    fD) No instances of a Quadrilateral object can be created in a program.,m Anv subclasses of the Quadrilateral classgrzzqprovide implemgntatio{t(/' .oi"fortheperimeterandareamethods.'\'-, bo u{!l\ .,, :.,A1\6vf,'w!- rWhich represents correct /* implementation cod'etor?

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

    nyBotRight = botRight; '(A) I only(B) II onlv@ :ntonty(D) I and II only(E) II and III onlY

    */ for the Rectangle construc-

    I t,I:

    nA F

  • 8/2/2019 Computer Science Spring Break

    10/24

    16 Practice ExamsRefer to the Parallelogram and Square classes below.

    public class Parallelogran extends Quadrilateral{/ /priv.ate instaace varlables . end constructor not'Shownpublic 1nt peri.netero{ /*, inplementati.on not shown */ }pub11c int areao{ /* implementation not shown *,/ })

    public class Square extends Rectangle{/ /private instance variables and constructor not shownpublic int perimetero{ /* inplenentation uot shown *,/ }public int areao{ /* inplementation not shown x/ }]

    Consider an Arraylist quad.List whose elements are of typeRe 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 quadlist)t for (Quadrilateral quad : quadlist)System.out.println("Area of " * quad.getlabelso* 'r is il + quag..areaO) i u,_i ..: ,r l; {"*\*_a"* ,i y v'./. l ;A ltt\..l

    16.

    l$Kfuat is the effect of executing this meth6d?\$) The area of each Quadrilateral in quad.List will betr\! compile-time error will occur, stating that thereabstract class Quadrilateral.printed.is no area method in

    (C) A compile-time error will occur, stating that there is no getlabels methodin classes Recta-ngle, Para11e1og1am, of Square.(D) A NullPointerExceptionwill be thrown.(E) A ClassCastException will be thrown.

    GO ON TO THE NEXT PAGE,

  • 8/2/2019 Computer Science Spring Break

    11/24

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

    / / postconditionpublic static void doSonething(List Iist, int i, int j){

    17

    \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 at 5.(C) Replaces in list the object indexed at j wirh the object indexed at i.(D) Replaces in list the objects indexed at i and 5 with tenp.tre) Interchanges in list the objects indexed at i and j.\_-.,'18. Consider the NegativeReal class below, which defines a negative real numberobject.

    public class NegativeReal{ private Double nyNegReal ;//constructor. Creates a NegativeReal object whose value is nr:m.//Precondition: num ( 0.public NegativeReal (double num){ /* implementation not shown x,/ }//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

    SomeType temp = 1i.st.get(i);list . set (i, list . get (j ) ) ;list. set (j , tenp) ;)

    -3.5-8.97-5.0-2.487-0.2

    return (int) (getValueo + 0.5);

    i ..e ,{ v-''-*,\: \.r r'-\\;0u-e-r*L*'

    -4-9-5-20/* implernentation */ of getRounded produces the desired postcondition?eturn (int) (getValueO - 0.5); e. *3,5 *,5 r , oZ ', !& , E L-*r]Ql r"trrrn (int) getValueO;-.OJ .-r e t*"rlr- (.4pub1 e)' '(etvatrue C)'-:o'5 ) ;

    qId-fdYU v

    it,rJL, L ',1 h ; ";tE) return (doulrH-gaflfelueO ;GO ON TO THE NEXT PAGE.

  • 8/2/2019 Computer Science Spring Break

    12/24

    18 Practice ExamsConsider the following method.

    public static void whatslt(int n){' if(n>10)whatslt (n / 70);System.out.print(n % 10) ;]\7hat will be output as a resuk of the method call whatslt (347)?(A) z+(B) +z(C) zs+@) 243

    \r1\!U'. _!\.-'-\". E: I

    I

    i r. \'"3''

    ,t-r\d, l:\. ./

    19.

    I'l. r'JI

    "t

    r/V r ^i,r.r9 ' Il-.tt -",",t

    i11!

    t-ii

    , t*r'tY, 20. Alargelistof numbersistobesortedintoascendingorder. Assumingthata"datamovement" is a swap or reassignmenr of an elemenr, which of the following is atrue 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 initialarrangement of elements.(C) The number of comparisons for insertion sort is independent of the initialarrangement of elements.@) The number of. data movements in selection sort depends on the initial ar-rangement of elements.(E) The number of da:,z movements in insertion sort is independent of the ini-tial arrangement of elements.S., C( c-l

    dau$-'b -'

    ! f^.-r+^.-t #Utrvr,UJf fli'i:..,$ -L .u{/ .*.,.v."{,".ry^

    iII

    t'*-u--r.1 - ,r!rrr*r-V-"fr{

    GO ON TO THE NEXT PAGE.

  • 8/2/2019 Computer Science Spring Break

    13/24

    Practice Exam One / Diagnostic Test 1921. Refer to the definitions of classone and ClassTvo below.

    public class Class0ne{ public void nethodOneot)//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 thatClass0ne and ClassTwo have default constructors.C1ass0ne cl = new CLass0neo;Class0ne c2 = new Cl-assTwoO i

    !(lhich of the following method calls will cause an error?Icl.nethodrroO;- h, I Vl" *M L

    IIc2.nethodTwoO; nn. Uf , *ulAdIIIc2.nethod0neO.J) h^-[.{^-! \ i q .l(A) None(B) I only(C) tr onlyQ) Itr onlYry Iandtronly

    \

    Ls l^e+ f u J,^**

    o.