Sie sind auf Seite 1von 11

UNIT 4 REVIEW (R1 x17 9/04; R2 x16 11/06; R3 random 11/07) NOTES: The test will have multiple-choice

ice questions and will have a program using the String class. The test covers Lessons 13-15, and 18. The following is not included on this test: Lesson 1 Lesson 1! the "ase #tud$ Lesson 13: #tring "lass The String class is an e%cellent e%ample of the power of o&'ect-oriented programming: (euse of e%isting code: )ou are using a pre-e%isting class, which helps reduce the time in developing new programs. *nformation hiding: )ou don+t need to ,now the details of how the class is implemented- $ou 'ust need to ,now how to use the .pu&lic/ methods. )ou also don+t have direct access to the .private/ instance varia&les inside the String o&'ects. 0ata a&straction: )ou are manipulating a String o&'ect as an 1a&stract data t$pe2 .30T/ 4 it has 1attri&utes2 .in this case, the actual string stored in it/ and 1&ehaviors2 .methods/. (eminder - String is a reference t$pe, not a primitive t$pe .such as char/. 3s a result, assigning one String to another String copies the reference, which is the pointer to the location of the actual o&'ect. There are man$ methods of the String class. 5ach method returns a new String o&'ect .and does not affect the state of the original String o&'ect/. "67#T(8"T6( 95T:60#:
String string1; // declaration no String instantiated yet string1 = new String(); // instantiates an (empty) string String string2 = new String(Hello); // String declared and instantiated in one line String string3 = new String(string2); // copy constr!ctor" !sed to ma#e a copy o$ // string2 %& string3 also contains Hello // '()*+,('- the .oolean e/pression string2 == string3" is $alse here0 // since e1ery time the word new" is !sed2 a new o34ect is // instantiated and placed in a new memory location2 and there$ore // string2" and string3" point to 2 di$$erent memory locations; // on the other hand2 the .oolean e/pression string25e6!als(string3)" // is tr!e5

String string7 = 8ood3ye; // String declared and instantiated in one line // '()*+,('- the String class is !sed so o$ten that it is the only // class allowing this short%c!t instantiation o$ an o34ect2 // i5e5 not re6!iring the !se o$ the word new"5

;85() 95T:60#:
String string7 = new String(8ood3ye); int len = string75length(); // len == 9 char ch = string75char:t(;); // ch == 8" int pos1 = string75inde/<$(3ye); // pos1 == 7 int pos2 = string75inde/<$( o"); // pos2 = 1 int pos3 = string75inde/<$(/y=); // pos3 = %1

T(37#L3T5 95T:60#:
String String String String string7 = new String(8ood3ye); // note length = 9 lower = string75to>ower?ase(); // lower" contains good3ye !pper = string75to@pper?ase(); // !pper" contains 8<<,.A( s!31 = string75s!3string(7); // s!31" contains 3ye2 // which is the s!3string $rom inde/ 7 to the end o$ the string String s!32 = string75s!3string(;27) // s!32" contains 8ood2 // which is the s!3string $rom inde/ ; to inde/ 32 +<B inde/ 700 String s!33 = string75s!3string(729) // s!33" contains 3ye // note how 9" is a 1alid arg!ment e1en tho!gh it is one greater // that the last 1alid inde/0 See 3elow $or 1alid arg!ment in$o5 String s!37 = string75s!3string(727) // s!37" contains

<<< 76T5: valid arguments to method su&string./ must meet these rules: 1. = >? argument >? length of string @. argument1 >? argument@ <<< *f invalid argument.s/ are used, String*nde/<!t<$.o!nds(/ception occurs. <<< :ere are some e%amples of invalid arguments:
String String String String string7 = new String(8ood3ye); s!31 = string75s!3string(C); s!32 = string75s!3string(72 C); s!33 = string75s!3string(72 3); // // // // note length = 9 C & length C & length 7 & 3

"69A3(*#67 95T:60#:
String string7 = new String(8ood3ye); String stringD = new String(8ood3ye); /E E the $ollowing .oolean e/pressions in these selection str!ct!res E are all tr!eE/ i$ (string75e6!als(stringD)) 555 i$ (stringD5e6!als(string7)) 555 i$ (stringD5e6!als(8ood3ye)) 555

i$ (stringD5e6!als*gnore?ase(8<<,.A()) 555 /E E the $ollowing is $alse E/ i$ (string7 == stringD) 555

/E E e/amples o$ method compareBo"2 which chec#s dictionary order E o$ 2 strings2 ignoring !pper/lowercase2 and ret!rns a n!meric 1al!e E/ int n!m1 = string75compareBo(8<<,.A(); // n!m1 == ; // %& 2 strings are the same n!m1 = string75compareBo(apples); // n!m1 & ; // %& arg!ment comes $irst n!m1 = string75compareBo(oranges); // n!m1 F ; // %& string7 comes $irst

There are times where $ou ma$ need to convert &etween a char and a String t$pe. To do so:
// char to stringchar ch1 = a"; String str = G ch; // // string to charchar ch2 = str5char:t(;);

str" now contains the string a // ch2" now contains the char a"

Lesson 1B: *nheritance *nheritance is one of the fundamental principles of o&'ect-oriented programming. *t is a powerful technique allowing a programmer: to reuse e%isting code to avoid duplication of code to allow e%tension of previous wor, Civen a more generaliDed class, called a superclass or parent class or &ase class, $ou can define a new class, called a su&class or child class or derived class, that inherits the characteristics of the parent .i.e. all the instance varia&les and methods/ and also provides new capa&ilities. Eava supports onl$ single inheritance .not multiple inheritance/. 3 child class can inherit characteristics from onl$ one parent. .6n the other hand, a parent can have more than one child class./ *nheritance can also e%tend over several 1generations2 of classes. *n designing classes and su&classes, one can sa$ that a particular subclass is a 1,ind of2 superclass. For e%ample, a Student is a 1,ind of2 Person- and a High School Student is a 1,ind of2 Student. *f $ou cannot appl$ this wording &etween a su&class and its superclass, the class hierarch$ is pro&a&l$ not designed appropriatel$G

To derive a su&class: use x! nd" to derive a su&class use #ro! $! d instance varia&les 4 this allows access &$ the class and all su&classes, &ut not access &$ the pu&lic use "%# r() to access the .immediate/ parent+s constructor note that a su&class inherits all the methods from its superclass- it can define new methods .that are not in the superclass/ andHor o& rr'd e%isting methods .i.e. provide a replacement method with the same method signature &ut different code &od$/ if the su&class overrides a method in the superclass, $ou can use "%# r(method_name() to access the method of the parent (eminder: The first line in the constructor of a su&class must &e a call to its parent+s constructor. *f there is no such e%plicit call, the compiler will implicitl$ call the parent+s default constructor .the constructor that has no arguments/. *f the parent has no default constructor in that case, it will cause a compiler error. Ihen a su&class overrides a method inherited from its superclass, then it needs to &e determined which version of the method to e%ecute. This is &ased on the data t$pe of the o&'ect that calls the method. This same determination is made when code inside one of these classes calls an overridden method - unless the prefi% Jsuper.+ or the prefi% Jthis.+ is used. .#ee e%amples in Lesson supplement 19ore 3&out *nheritance2./ >continuedK

class Herson I protected String my+ame; protected int my:ge; protected String my8ender; // !se protected instead o$ private to allow s!3class // access to instance 1aria3les p!3lic Herson(String name2 int age2 String gender) I my+ame=name; my:ge = age; my8ender = gender; J p!3lic String toString() I ret!rn +ame- G my+ame G 2 age- G my:ge G 2 gender- G my8ender; J J class St!dent e/tends Herson // !se extends to deri1e a s!3class I protected String my*d+!m; protected do!3le my8H:; // this class has a total o$ five instance 1aria3les // 3 inherited $rom the parent class pl!s 2 o$ its own p!3lic St!dent (String name2 int age2 String gender2 String id+!m2 do!3le gpa) I s!per(name2 age2 gender); // here2 super e/ec!tes the s!perclass constr!ctor // !sing it a1oids d!plication o$ code in the s!per // and s!3classes; // KH(+ super *S @S(, *+ BH( ?<+SB'@?B<'2 *B )@SB .( // BH( L*'SB SB:B()(+B // init o$ instance 1aria3les !ni6!e to St!dentmy*d+!m = id+!m; my8H: = gpa; J p!3lic String toString() // overrides toString() method in Herson class I ret!rn s!per5toString() G 2 *,- G my*d+!m G 2 gpa- G my8H:; // to a1oid d!plication o$ code2 !tili=es the toString() // method in the Harent class !sing super.toString()

J J

.*n Eava, the <34ect class is the root class from which a)) classes are derived. Ihen $ou define a new class that does not include the word Je/tends+, it automaticall$ assumes Je/tends <34ect+. The <34ect class has a small num&er of methods that

ma,e sense for all classes, such as the toString method, and their implementations t$picall$ get redefined in the derived classes./ 8nli,e a class, an interface is a set of methods with no implementations. 3 class implements an interface &$ suppl$ing code for all the interface methods. 3 class can e%tend onl$ one other class .single inheritance/ and can implement one or more interfaces.
p!3lic interface (mploya3le I // a set o$ method signat!res J p!3lic class Beacher extends Herson implements (mploya3le I 555 J

*nterfaces are useful for: declaring a common set of methods that one or more classes should implement providing a relationship &etween dissimilar classes without imposing an unnatural class relationship )ou are onl$ responsi&le for understanding the concept of interfaces and for understanding code that implements an interface- $ou will not &e as,ed to write code that defines an interface. Lesson 15: (ecursion (ecursion occurs when a method contains code that calls itself. Ihen a recursive call is made, the current computation is temporaril$ suspended and placed on the stac,, and a completel$ new cop$ of the method is used to evaluate the recursive call. (ecursion requires a &ase case, where no recursive call is made. Ihen the &ase case is reached, the recursion will unwind and result in a final answer. *t is critical that recursive calls move toward the &ase case, otherwise the program ultimatel$ crashes. 3n$ recursive algorithm can &e implemented iterativel$, &ut sometimes onl$ with difficult$. :owever, a recursive solution will alwa$s run more slowl$ due to the overhead of saving information onto the stac, and then retrieving it. )ou need to ,now how to evaluate recursive code, &ut not how to write it. #ee sample practice at the end of this review. Lesson 18: Loolean 3lge&raHLoop Loundaries- (andom num&er generation L66L537 3LC5L(3HL66A L68703(*5#: 0e9organ+s Law: G.3 or L/ ?? G3 and GL

G.3 and L/ ?? G3 or GL M where J3+ and JL+ represent an$ Loolean e%pressionN 5%amples of negating a Loolean e%pression: G.% ?? 5/ is equivalent to % G?5 G.% > 5/ is equivalent to % K? 5 0e9organ+s Law can &e useful in determining the test condition for a while or do% while loop. *f $ou want the loop to end when a certain condition is true, then the loop should continue while the condition is false. *t can &e helpful to use a truth ta&le to evaluate comple% Loolean e%pressions. The &asic truth ta&les for 370 .OO/, 6( .PP/ and 76T .G/ are: 3 F F T T L 3 OO L F T F T 3 PP L F F F T F T T T G3 T T F F

For e%ample, let+s sa$ $ou are as,ed to evaluate when the following e%pression is true: G3 OO .3 PP L/ )ou can ma,e a truth ta&le and see what com&ination of 3 and L values ma,e this e%pression true: start with columns for 3 and L, containing the four possi&le com&inations of True and False ma,e additional columns for each portion of the e%pression: G3- 3 PP L ma,e a column for the final e%pression see which case.s/ ma,e the final column True 3 F * T T L G3 F T F T 3 PP L T T F F F T T T G3 OO .3 PP L/ F T F F

answer: onl$ when 3 is False and L is True

(37069 789L5( C575(3T*67: There are man$ computer programs that can &enefit from seemingl$ random &ehavior, such as computer games, screen savers, and simulations. *t is &ased on the concept of generating a 1pseudorandom2 numeric value that is &ased on the computer cloc, time .which is used a 1seed2 value to help it appear to &e random/.
do!3le r = )ath5random(); // 1al!e in range ;5; F= r F 15;

*t is often helpful to modif$ the output as needed &$ doing one or more of these: <scaling the range
double r = 3 * Math.random(); // value in range 0.0 <= r < 3.0

< shifting the range


double r = Math.random() + 2; // value in range 2.0 <= r < 3.0

< truncating the output to give integer values


do!3le r = (int) (3E )ath5random()); // 1al!e in range ; F= r F= 2

Lesson 1 : Te%t File *H6 .#ummariDed here, &ut no! on Un'! 4 T "!/ 3n .3#"**/ te%t file is a sequential access file, one that must &e read from the &eginning of the file and then element &$ element .rather than &eing a&le to 'ump to an$ location in the file/. The file is organiDed &$ lines, each ending with an eoln .end of line/ mar,er .that is dependent on the operating s$stem/. The file ends with one eof .end of file/ mar,er. The te%t file is li,e one long stream of 3#"** codes. *n this course $ou are using a simplistic set of file input and output classes provided &$ *"T. To write to file: import chn5!til5E; 555 Lile<!tp!t o!tLile = new Lile<!tp!t(my$ile5t/t); // i$ yo! don"t want to wipe o!t the contents o$ an e/isting // $ile2 yo! can say- 555 Lile<!tp!t(my$ile5t/t2 append); o!t$ile5println(hello); o!t$ile5print(and good3ye); 555 o!t$ile5close(); // i$ yo! $orget to incl!de this line2 the program might end // 3e$ore the operating system has $inished writing data // to the $ile and the last data might get lost The resulting output file m$file.t%t will contain: hello and good3ye To read from the a&ove file: Lile*np!t inLile = new Lile*np!t(my$ile5t/t); while (inLile5has)oreBo#ens()) // 3ecomes $alse when detects eo$ mar#er I inLile5read>ine(); // the same set o$ methods are a1aila3le to yo! as in // the ?onsole*< class- read>ine()2 readBo#en()2 read*nt()2 // read,o!3le() 555 J

+ra$!'$ ,% "!'on" 1. The Loolean e%pression .3/ .L/ ."/ .0/ .5/ .3 OO L/ PP 3 is true

whenever 3 is true whenever L is true whenever either 3 is true or L is true whenever &oth 3 is true and L is true in all cases G. .3 > L/ OO ." K 0/ / is equivalent to which of the

@. The Loolean e%pression following e%pressionsQ .3/ .L/ ."/ .0/ .5/

.3 > L/ PP ." K 0/ .3 K? L/ OO ." >? 0/ .3 K? L/ PP ." >? 0/ .3 K L/ OO ." > 0/ .3 K L/ PP ." > 0/

3. Civen the following code segment where the user is to choose from a menu option 1, @ or 3:
int option; ?onsole*< inp!t = new ?onsole*<(); do I System5o!t5print(M ?hoose an option (12 2 or 3)- M); option = inp!t5read*nt(); i$ (Fconditional statement&) System5o!t5println(M*n1alid inp!tM); J while Fconditional statement&;

Cive two different versions .0e9organ equivalents/ of an appropriate >conditional statementK that guards against invalid input.
MNo! that the most ro&ust t$pe of code segment for accepting user input is one that not onl$ ,eeps repeating until user enters valid input, &ut also notifies user when input is invalid.N

-n". r/ Rersion 1: Rersion @:

B. 3ssume that onl$ positive parameters are passed to method )ystery3 &elow. Ihich e%pression represents the action of )ystery3 Q
p!3lic static int )ystery3(int a2 int 3) I i$ (; == a) ret!rn 1; else ret!rn 3 E )ystery3(a%123); J

.3/ .L/ ."/ .0/ .5/

aS& a<& a& &a aG .a factorial/

5. "onsider method 8!ess2 &elow.


p!3lic static int 8!ess2(int n) I i$ (n F= 1) ret!rn 1; else I i$ (n N 2 == 1) ret!rn n G 8!ess2(n % 1); else ret!rn n % 8!ess2(n % 1); J J

Ihat value does 8!ess2(9) returnQ .3/ .L/ ."/ .0/ .5/ = 1 B 8 13

. Civen the following method:


p!3lic static String Khats@p (String str12 String str2) I int inde/ = str15inde/<$(str2); i$ (inde/ 0= %1) str1 = str15s!3string(;2 inde/) G str15s!3string(inde/ G str25length()); ret!rn str1; J

Ihat does this line of code outputQ


System5o!t5print( Khats@p(Sponge.o3S6!areHants2 S));

.3/ .L/ ."/ .0/ (E) -n". r"

ponge.o36!areHants ponge.o36!areHant Sponge.o3S6!areHants ponge.o3S6!areHants Hatric#

1. 3 @. " 3. The loop should stop if Joption+ is 1 or @ or 3. #o the test condition needs to &ecome false in an$ of those cases- otherwise the condition needs to &e true. There are a num&er of wa$s to code this test condition: a. G .option ?? 1 PP option ?? @ PP option ?? 3/ &. .option G? 1 OO option G? @ OO option G?3/ Mwhich is 0e9organ equivalent of answer a.N c. G.option K? 1 OO option >?3/ d. .option > 1 PP option K 3/ Mwhich is 0e9organ equivalent of answer c.N B. 0 5. 0 .0

Das könnte Ihnen auch gefallen