Programming Abstractions in Java, 2017 Edition Solution Manual

Get the textbook answers you need with Programming Abstractions in Java, 2017 Edition Solution Manual, a solutions manual packed with clear and concise explanations.

Ella Hall
Contributor
4.2
60
5 months ago
Preview (16 of 65 Pages)
100%
Purchase to unlock

Page 1

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 1 preview image

Loading page image...

Answers to review questions from Chapter 11.When you write a Java program, do you prepare a source file or a class file?A source file2.What characters are used to mark comments in a Java program?/*. . .*/3.What is the significance of each component in the package declarationpackageedu.stanford.cs.javacs2.ch1;eduindicates the educational domainstanfordindicates Stanford Universitycsindicates the Computer Science departmentjavacs1indicates that this package goes with the Java book for CS1ch1indicates that this package is associated with Chapter 14.How would you define a constant calledCENTIMETERS_PER_INCHwith the value 2.54?publicstaticfinaldoubleCENTIMETERS_PER_INCH=2.54;5.What is the name of the method that must be defined in every Java program?A public static void method namedmain6.What is meant by the termboilerplate?What is the boilerplate form of themainmethod usedthroughout this book?Boilerplaterefers to idiomatic programming patterns that are repeated in different programs buthave no real significance for the programmer. The boilerplate form of main ispublicstaticvoidmain(String[]args){newclassname().run();}7.Indicate which of the following are legal variable names in Java:a.xLegalb.formula1Legalc.average_rainfallLegald.%correctIllegal (begins with%)e.shortIllegal (reserved word)f.tinyLegalg.totaloutputIllegal (contains a space)h.aVeryLongVariableNameLegali.12MonthTotalIllegal (begins with a digit)j.marginal-costIllegal (contains a hyphen)k.b4handLegal (but perhaps too clever)l._stk_depthLegal8.What are the two attributes that define a data type?Types are defined by adomainand aset of operations.

Page 2

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 2 preview image

Loading page image...

Page 3

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 3 preview image

Loading page image...

9.What sizes does Java assign to the typesbyte,short,int, andlong?byte= 8 bitsshort= 16 bitsint= 32 bitslong= 64 bits10. What coding system does Java use for characters?Unicode11. What does ASCII stand for? What relationship does the ASCII code have to the code used to representcharacters in Java?American Standard Code for Information InterchangeThe ASCII code matches the first 256 characters in the Unicode standard.12. List all possible values of typeboolean.falseandtrue13. What statements would you include in a program to read a value from the user and store it in thevariablex, which is declared as adouble?You would first need to declare a scanner usingScannerscanner=newScanner(System.in);Later in the program you could read the value ofxusing lines like this:System.out.print("Enterx:");doublex=scanner.nextDouble();14. Indicate the values and types of the following expressions:a.2+35 (int)b.19/53 (int)c.19.0/53.8 (double)d.3*6.018.0 (double)e.19%54 (int)f.2%72 (int)15. What is the difference between the unary minus and the subtraction operator?The unary minus operator is written before a single operand and denotes negation, as in-x. Thesubtraction operator is written between two operands as inx-2.16. Calculate the result of each of the following expressions:a.6+5/4-34b.2+2*(2*2-2)%2/22c.10+9*((8+7)%6)+5*4%3*2+142d.1+2+(3+4)*((5*6%7*8)-9)-1042

Page 4

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 4 preview image

Loading page image...

17. What does the termtruncationmean?Truncationconverts a floating-point number to an integer by throwing away any digits after thedecimal point. Thus, the floating-point number 3.9999 truncates to the integer 3.18. What is atype castand how do you indicate one in Java?Atype castis used to indicate conversion of one type to another.In Java, type casts are writtenby enclosing the type name in parentheses before the value to be converted, as in the expression(int)x, which truncatesxto an integer.19. How do you specify a shorthand assignment operation?Shorthand assignment operators are written by writing the operator in front of the equal signused for assignment, as inbalance+=deposit;20. What is the difference between the expressions++xandx++?Both expressionsincrement(add one to) the value ofx.The difference is the value of theexpression.The expression++xreturns the incremented value; the expressionx++returns theoriginal value before the increment.21. What is meant byshort-circuit evaluation?Short-circuit evaluationevaluates only as much of an expression as is necessary to determine theresult.Java uses short-circuit evaluation to evaluate the logical operators&&and||.With&&,for example, there is no need to evaluate the right operand if the left operand istrue.22. Write out the general syntactic form for each of the following control statements:if,switch,while,andfor.if(condition)statementif(condition)statementelsestatementswitch(e){casec1:statementsbreak;casec2:statementsbreak;...more case clauses...default:statementsbreak;}while(conditional-expression){statements}for(init;test;step){statements}

Page 5

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 5 preview image

Loading page image...

23. Describe in English the operation of theswitchstatement, including the role of thebreakstatementat the end of eachcaseclause.When the program executes aswitchstatement, it evaluates the control expression andcompares it against the valuesc1,c2, and so forth, each of which must be a constant. If one of theconstants matches the value of the control expression, the statements in the associatedcaseclause are executed. When the program reaches thebreakstatement at the end of the clause, theoperations specified by that clause are complete, and the program continues with the statementthat follows the entireswitchstatement.If none of the expression match the value of thecontrol expression, the program executes the statements in thedefaultclause, if any.24. What is asentinel?What is the general form of theread-until-sentinelpattern?Asentinelis a value used to indicate some kind of special processing and often signals the end ofa list of input values.25. Whatforloop control line would you use in each of the following situations?a.Counting from 1 to 100for(inti=1;i<=100;i++)b.Counting by sevens starting at 0 until the number has more than two digitsfor(inti=0;i<100;i+=7)c.Counting backward by twos from 100 to 0for(inti=100;i>=0;i-=2)26. Define each of the following terms:class, object, method,instance variable,subclass,andsuperclass.Aclassis a template for data objects that share a common representation and set of operations.Anobjectis a data value that is an instance of a particular class.Amethodis a sequence of program steps that have been collected together and given a name.Aninstance variableis a particular data value stored within an object.Asubclassis a class that extends the behavior of an existing class, which becomes itssuperclass.27. True or false: In Java, there can be many objects that are instances of a class.True.28. In Figure 1-12, what subclasses are shown for the classArthropoda?The direct subclasses areCrustacea, Insecta,andArachnida.The descendents ofInsecta(Hymenoptera, Formicidae, Lasius,andniger) are indirect subclasses ofArthropoda.29. What two features does this chapter identify as the most important aspects of the object-orientedprogramming model?Encapsulation and inheritance.

Page 6

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 6 preview image

Loading page image...

Answers to review questions from Chapter 21.Explain in your own words the difference between amethodand aprogram.Amethodcomputes a value or performs some operation on behalf of the code for a program. Aprogramexecutes computation on behalf of a user. A program typically includes many methods.2.Define the following terms as they apply to methods:call,argument,return.In programming terminology, the process of invoking a method is referred to ascallingthatmethod. In the process of making a call, the caller can provide data to the method in the form ofarguments,which are a set of local variables that are initialized from the values written inside theparentheses that designate the call. When the method completes its work, itreturnsto its caller,often passing back a value as a result.3.Can there be more than onereturnstatement in the body of a method?Yes. A method can include any number ofreturnstatements.4.What is astatic method?Astatic methodis a method associated with a class rather than with a specific object.Staticmethods are called by including the class name and a dot before the method name.5.How would you calculate the trigonometric sine of 45° using theMathclass?Math.sin(Math.toRadians(45))6.What is apredicate method?Apredicate methodis a method that returns a Boolean value.7.Describe the difference in role between animplementerand aclient.Theimplementeris responsible for writing the actual code that carries out an operation.Theclientinvokes that code to perform the operation but need not understand thedetails for doingso.8.What is meant by the termoverloading?How does the Java compiler usesignaturesto implementoverloading?In Java, the termoverloadingrefers to the fact that you can define several different methods withthe same name, as long as each method has a differentsignature,which indicates the number andtypes of the arguments.When the Java compiler sees a call to an overloaded method with aparticular name, it examines the argument values to see which version of that method isrequired.9.What is astack frame?Astack frameis the region of memory used to hold the values of local variables during a methodcall. The frame is created when the method is called and deleted when the method returns.

Page 7

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 7 preview image

Loading page image...

10. Describe the process by whichargumentsare associated withparameters.Arguments and parameters are matched by their order in the argument list.The names of theparameters have no bearing on the association process.11. Variables declared within a method are said to belocal variables. What is the significance of the wordlocalin this context?Local variables can be used only within that method.Neither the caller nor any method calledfrom inside a method has access to those local variables.12. What is the difference betweeniterationandrecursion?Iteration refers to the process of performing repeated calculations by using a loop to execute thesame code.13. What is meant by the phraserecursive leap of faith?Why is this concept important to you as aprogrammer?Therecursive leap of faithrefers to the idea that, in writing a recursive solution, you can assumethat smaller instances of the problem work and then reassemble those solutions to solve theoriginal problem.If you fail to adopt the recursive leap of faith, you are forced to trace theoperation of the program all the way down to the simple cases, which often makes the process toocomplex to follow.14. In the section entitled “Tracing the recursive process,” the text goes through a long analysis of whathappens internally whenfact(4)is called.Using this section as a model, trace the execution offib(3), sketching out each stack frame created in the process.Step 1:Step 2:Step 3:

Page 8

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 8 preview image

Loading page image...

Step 4:Step 5:Step 6Step 7:Step 8:

Page 9

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 9 preview image

Loading page image...

Step 9:Step 10:Step 11:Step 12:Step 13:Step 14:

Page 10

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 10 preview image

Loading page image...

15. What is arecurrence relation?Arecurrence relationis an expression defining each new element of a sequence in terms of earlierelements.16. Modify Fibonacci’s rabbit problem by introducing the additional rule that rabbit pairs stop reproducingafter giving birth tothreelitters.How does this assumption change the recurrence relation?Whatchanges do you need to make in the simple cases?The new recurrence relation must subtract out the rabbits that are too old to reproduce, whichare all of those born more than four months ago.The recurrence relation therefore looks likethis:tn=tn-1+tn-2tn-5The simple case must now take account of the fact that the value ofnmay now range intonegative territory, when there were no rabbits.The code for the revised rabbit problem lookslike this:privateintrabbits(intn){if(n<=0){return0;}elseif(n==1){return1;}else{returnrabbits(n-1)+rabbits(n-2)-rabbits(n-5);}}17. How many times isfib(1)called whenfib(n)is calculated using the recursive implementationgiven in Figure 2-5?The methodfib(1)is calledfib(n)times.18. What is awrapper method?Why are wrapper methods often useful in writing recursive methods?Awrapper methodis a method whose only role is to set things up for a call to a more generalrecursive method that does all the work.In many situations, the recursive process requiresadditional state information that the wrapper method can provide.19. What would happen if you eliminated theif(n==1)check from the methodadditiveSequence,so that the implementation looked like this:intadditiveSequence(intn,intt0,intt1){if(n==0)returnt0;returnadditiveSequence(n-1,t1,t0+t1);}Would the method still work? Why, or why not?The method would still work. In the absence of the check, the method calls itself recursively with0 as the first argument and the value oft1as the second. Sincenwill then be 0 in the recursivecall, the method will return the original value oft1, just as before.

Page 11

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 11 preview image

Loading page image...

Answers to review questions from Chapter 31.What is the difference between acharacterand astring?Acharacteris a data value that represents a single character of text.Astringis a sequence ofcharacters.2.True or false: In Java, you can determine the length of the string stored in the variablestrby callinglength(str).False. You need to callstr.length().3.What does it mean to say that theStringclass isimmutable?Animmutable classhas the property that the value of an object cannot be changed after it iscreated.Strings in Java are immutable, which means that none of the methods in theStringclass ever changes a string; string methods instead return a new string containing the updatedvalue.4.If you calls1.concat(s2), which string is thereceiver?Thes1string is the receiver.5.What is the effect of the+operator when it is used with two string operands?What happens if oneoperand is a string, but the other is of some numeric type?The+operator in Java signifies concatenation (joining two strings together end to end) if eitherargument is a string.If only one argument is a string, Java converts the other to its stringrepresentation.6.True or false: The index positions in a string begin at 0 and extend up to the length of the string minus1.True.7.What are the arguments to thesubstringmethod? What happens if you omit the second argument?The arguments tosubstringare the first index position of the desired substring and the indexof the position immediately following the desired substring.If you omit the second argument,substringreturns a substring that extends through the end of the string.8.What islexicographic ordering?Lexicographic orderingis similar to alphabetical ordering but uses the ordering imposed by theunderlying Unicode values of the characters.9.What happens in Java if you try to use the==operator to test whether two strings are equal?The==operator tests whether two strings areidentical(i.e., whether they are the same object)rather than whether they contain the same characters.

Page 12

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 12 preview image

Loading page image...

10. Describe how thecompareTomethod uses the return value to indicate the relative ordering of twostrings.ThecompareTomethod returns 0 if the strings are equal, a positive value if the receiver string isgreater than the argument, and a negative value if the receiver string is smaller than theargument.11. What value doesindexOfreturn if the pattern string does not appear?The sentinel value1.12. What is the significance of the optional second argument toindexOf?The second argument represents the starting position for the search.13. What effect does the following statement have on the value ofstr?str.trim()Thetrimmethod returns a copy of the original string after removing any leading or trailingwhitespace characters. As written, however, the receiver stringstris unaffected.14. What is the correct way to achieve the effect clearly intended by the expression in the precedingquestion?str=str.trim();15. Suppose that you have declared and initialized the variablesas follows:Strings="hello,world";Given that declaration, what is the value of each of the following calls:a.s+'!'"hello,world!"b.s.length()12c.s.charAt(5)','d.s.indexOf('l')2e.s.indexOf("l",5)10f.s.replace('h','j')"jello,world"g.s.substring(0,3)"hel"h.s.substring(7)"world"i.s.substring(3,5)"lo"j.s.substring(3,3)""16. What is the result of each of the following expressions? (For calls tocompareTo, simply indicate thesign of the result.)a."ABC".equals("abc")falseb."ABC".equalsIgnoreCase("abc")truec."ABC".compareTo("ABC")0d."ABC".compareTo("AB")+e."ABC".compareTo("abc")f."ABC".endsWith("c")false

Page 13

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 13 preview image

Loading page image...

17. What is the pattern for iterating through each character in a string?The second argument represents the starting position for the search.18. How does the pattern in question 17 change if you want to iterate through the characters in reverseorder, starting with the last character and ending with the first?for(inti=0;i<str.length();i++){...body of loop that uses the characterstr.charAt(i)...}19. What is the pattern for growing a string through concatenation?Stringstr="";for(whatever loop header line fits the application) {str+=the next substring or character;}20. What is the result of each of the following calls to theCharacterclass:a.Character.isDigit(7)falseb.Character.isDigit('7')truec.Character.isLetter('7')falsed.Character.toUpperCase(7)7e.Character.toUpperCase('A')'A'f.Character.toLowerCase('A')'a'

Page 14

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 14 preview image

Loading page image...

Answers to review questions from Chapter 41.What are the principal differences between atext fileand astring?The two main differences are (1) the information stored in a file is permanent and (2) files areusually read sequentially.2.What are the three steps necessary to read the contents of a text file?Opening the file, reading the data, and closing the file.3.What is anexception?Anexceptionis an unusual condition outside the normal program flow..4.What is the general form of thetrystatement?try{Block of code in which the exception can be caught.}catch(typevar){Code to respond to an exception of the specified type.}...other catch clauses if necessary...5.Trueorfalse:CatchingtheIOExceptionraisedbytheclassesinthejava.iopackage is optional.False. Java programs must catch these exceptions.6.Suppose that you have a string variablefilenamethat contains the name of a text file.Whatstatements would you write to create a reader variable namedrdthat you could then use to read linesfrom this file?BufferedReaderrd=newBufferedReader(newFileReader(rd));7.Why does thereadmethod return anintrather than achar?Thereadmust be able to signal the end of the file, which is represented by the integer1. Thatvalue needs to be outside the character range, because the file could contain any combination ofcharacters.8.How do you detect the end of a file if you are usingreadLineto read it line by line?ThereadLinemethod returnsnullas a sentinel value.9.What three writer classes are typically involved in opening a text file for output?FileWriter,BufferedWriter, andPrintWriter.10. True or false: Java 5.0 reintroduced theprintfmethod, which was originally designed for theprogramming language C.True.11. What is aformat code?Aformat codeis a sequence of characters beginning with a percent sign and ending with a keyletter that specifies howprintfshould format a value.

Page 15

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 15 preview image

Loading page image...

12. How do you include a percent sign in aprintfformat string?Use two consecutive percent signs.13. In your own words, describe the differences between the%e,%f, and%gformat codes.The%eformat code always displays its value using scientific notation with the lettereprecedingthe power of ten used as the exponent.The%fformat code always displays its value as afloating-point value without an exponent.The%gformat code uses either scientific notation orfloating-point conversion, whichever produces the most compact result.14. What is the difference in the output produced by the%eand%Eformat codes?The%eformat code uses a lowercaseeto signify the exponent in scientific notation.The%Eformat code uses an uppercaseE.15. The constantPIin thejava.lang.Mathclass is defined aspublicstaticfinaldoublePI=3.141592653589793238;Whatprintfformat string would you use to produce each line of the following sample run:"%17.15f""%8.6f""%17.15e""%8.6E""%15.9f""%08.4f"16. What Java class implements the simplest strategy for reading formatted input?TheScannerclass.17. What do the letters in the file type.csvstand for?Comma-separated values.18. What call would you invoke on aScannerobject to read.csvfiles?scanner.useDelimiter(",");19. What Java class makes it possible to open files using an interactive dialog?TheJFileChooserclass.20. What is the purpose of athrowsclause in a method definition?Thethrowsclause indicates to the Java compiler that this method may throw the specifiedexceptions.

Page 16

Programming Abstractions in Java, 2017 Edition Solution Manual - Page 16 preview image

Loading page image...

Answers to review questions from Chapter 51.What are the two characteristic properties of an array?An array is (1)orderedand (2)homogeneous.2.Define the following terms:element, index, element type, array length,andselection.Anelementis the value in a particular position in the array.Anindexis the integer that identifies the position number, which start at 0 in Java.Theelement typeis the type of each element, which must all be the same.Thearray lengthis the number of elements in the array.Selectionis the process of choosing a particular element by its index.3.Write declarations that create and initialize the following array variables:a)An arraydoubleArrayconsisting of 100 values of typedoubledouble[]doubleArray=newdouble[100];b)An arrayinUseconsisting of 16 values of typebooleanboolean[]inUse=newboolean[100];c)An arraylinesconsisting of 50 stringsString[]lines=newString[50];4.How do you determine the length of an array?By selecting itslengthfield, as inarray.length.5.The code for theGymnasticsJudgeprogram uses the following statement to prompt the user to entereach judge’s score:System.out.print("Enterscoreforjudge"+(i+1)+":");What is the reason behind adding 1 to the value ofi?Adding one to the index transforms it from the 0-based index scheme that Java uses to the morefamiliar style of numbering that starts at 1.6.In the code shown for the preceding exercise, are the parentheses around the expressioni+1necessary? Why or why not?The parentheses are necessary.Without them, the prompt string would start with the string"Enterscoreforjudge"followed by the value ofi, the digit 1, and a colon.7.Define the following terms:bit, byte,andword.Abitis a data value with exactly two states, typically denoted by0and1.Abyteis a combinedsequence of eight bits that can take on values between 0 and 255; a byte is also the smallestaddressable unit in memory. Awordis a longer collection of bits that represents the natural sizefor an integer in the hardware of the machine.8.What is the etymology of the wordbit?The wordbitfirst appeared in a publication by Claude Shannon as a contraction ofbinary digit.
Preview Mode

This document has 65 pages. Sign in to access the full document!

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Document Details

Related Documents

View all