Java how to program late objects 10th edition deitel solutions manual 1

Page 1

Solution Manual for Java How to Program Late Objects

10th Edition Deitel 0132575655 9780132575652

Full download link at:

Solution manual: https://testbankpack.com/p/solution-manual-for-java-how-to-programlate-objects-10th-edition-deitel-0132575655-9780132575652/

Test bank: https://testbankpack.com/p/test-bank-for-java-how-to-program-late-objects10th-edition-deitel-0132575655-9780132575652/

5

Functions and Methods:

ADeeper Look; enums and Tuples

2 Chapter 5 Functions and Methods: ADeeper Look; enums and Tuples

Self-Review Exercises

Section 5 1 Introduction

5.1 The key distinction between function and a method is that any function defined in a is a method

ANS: type (or class)

5.2 is Apple’s UNIX-based core ofOS Xand iOS.

ANS: Darwin

5.3 (True/False) enum constants must have values

ANS: False enum constants can have values, but that’s not required

5.4 You’llfrequently seeidentically named functions or,within atype, identicallynamed methods This isused to implement functions ormethods that perform similar tasksbut with different types and/or different numbers ofparameters

ANS: overloading

5.5 When parameter names are providedin a function definition, they must be used in the function call to label the corresponding arguments.

ANS: external

5.6 (True/False) Parameter names arealwaysrequired in initializer calls.

ANS: True

Section 5 2 Modules in Swift

5.7 (True/False) Swift apps are written by combining new functions and types, properties, methods,classes, structs and enums with predefined capabilities in the Swift StandardLibrary, the Cocoaand CocoaTouch frameworks, and other class libraries

ANS: True

5.8 (True/False) Free functions aresometimes called local functions

ANS: False. Actually, freefunctions are sometimescalled global functions.

5.9 Strings arecollections of

ANS: characters

5.10 An Equatable item can be compared with another item of the same type using the operator

ANS: ==

5.11 (True/False)Functions sort and sorted sort the contents of Dictionary objects sort modifies the original Dictionary’s contents and sorted returns a new Dictionary containing the sorted contents

ANS: False Actually these functions sort Arrays.

5.12 If youcreate aSwift-basedCocoa Framework project or Cocoa Touch Framework project, you can then reuse that framework in Cocoa and Cocoa Touch apps by importing it with the keyword.

ANS: import

Section 5.3 Darwin Module Using Predefined C Functions

5.13 To import the Darwin module,use the declaration

ANS: import Darwin

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Section 5 4 Multiple-Parameter Function Definition

5.14 What does the following function header indicate?

func maximum(x: Double, y: Double, z: Double) -> Double

ANS: This function header indicates that function maximum requiresthree Double parameters (x, y and z) to accomplish its task and returns a Double result

5.15 (True/False) The typeofeach argumentmust match the type ofthe corresponding parameteror beimplicitly convertible to the parameter’s type.

ANS: False The typeofeach argument must matchthe typeofthe corresponding parameter Swiftdoesnot allow implicit conversions.

5.16 (True/False) Swiftenablesyouto code the method parameters declaration

x: Double, y: Double

moreconcisely as

x, y: Double.

ANS: False Actually, declaring method parameters of the sametype as x, y: Double insteadof x: Double, y: Double isa syntax error atype isrequiredforeach parameter in the parameter list

5.17 Swift provides a max functionthat canbeused to compare twovalues ofthe same Comparable type all ofSwift’s numerictypes and are Comparable.

ANS: Strings

Section 5.5 Random-Number Generation

5.18 (True/False) The function arc4random takes no arguments and returns a random unsigned 32-bit integer in the range 0 (UInt32 min) to 4,294,967,295 (UInt32.max).

ANS: True

Section 5 6 1 Introducing Enumeration (enum) Types

5.19 (True/False) Ifavariable has an enum type, youcanassign enum constants to the variable usingthe shorthand notation: variableName = EnumConstantName

ANS: True

5.20 (True/False) If an enum type’sconstants represent sequential integer values, theycanbedefinedas a comma-separated list in one case, as in:

enum Months: Int { case January = 1, February, March, April, May, June, July, August, September, October, November, December }

In Months, each subsequent constantafter January has avalue onehigher than the value ofthe previous constant,so February is 2, March is 3, etc.

ANS: True

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Self-Review Exercises 3

4 Chapter 5 Functions and Methods: ADeeper Look; enums and Tuples

5.21 (True/False)Using enumeration constants (like Months.January, Months February, etc.) rather than literal integervalues (such as1, 2, etc ) makes codeeasier to readbut more difficult to maintain

ANS: False Actually, the wholepoint of using enumeration constants rather than literal integer values is to makecodemore readable and easier to maintain.

Section 5.6.2 Tuples and Multiple Function Return Values

5.22 When a tuple specifies names for its elements,you can access them by name using the syntax

ANS: dot ( )

5.23 What is the purpose ofthe underscores in the following statement?

let (_, _, sum) = rollDice()

ANS: When decomposinga tuple, if you need only some of the values, you can ignore individualvalues with the underscorecharacter.

5.24 To prevent a compilation error whenyouuse a value ofone numeric type where a different numeric type is expected, the compiler requires youto the value to the required type to force the conversion

ANS: cast

5.25 (True/False) Each numerictype represents a different range of values Disallowing implicit conversions thus forcing you to use explicit castsfor numeric conversions prevents unintentionalconversions between types This is another Swift feature that eliminates errors

ANS: True.

Section 5 6 4 Accessing the Raw Value of an enum Constant

5.26 Each enum constanthas a propertythat returns the constant’s raw value.

ANS: rawValue

Section 5 7 Scope of Declarations

5.27 (True/False) Any block may contain variable declarations

ANS: True

5.28 Hidden properties canbe accessed via the keyword

ANS: self

Section 5 8 Function and Method Overloading

5.29 The compilerdistinguishes overloaded functions by their a combination of the function’s nameand the number, types and orderof its parameters

ANS: signature

5.30 (True/False) Function calls cannot be distinguished byreturn type

ANS: True.

5.31 (True/False) Overloaded functions neednot have the same number ofparameters.

ANS: True.

Section 5.9 External Parameter Names

5.32 (True/False) You canalso define external parameter names that the caller is required to use when a function is called as is the case for allthe arguments to an initializer and anyarguments

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Self-Review

afterthe firstargumentin a method call This can help makethe meaningof each argumentclear to the programmer calling the function

ANS: True

5.33 (True/False) By default, the names of an initializer’s parameters and the names of a method’s parameters foreveryparameter after the firstareused astheir external names.

ANS: True.

5.34 Because the method name should referto the first parameter,Swift provides only a local parameter name for the first method parameter, then provideslocal and parameter names forall subsequent parameters

ANS: external

5.35 (True/False) You can requirea method’s caller to provide an external parameter name for the method’s first argument To do so, simply precede the parameter name with # to usethe local parameter nameas the external parameter nameor specify an external parameter name.

ANS: True

5.36 (True/False) In a function call, youmust explicitlyprovide an argumentforevery parameter

ANS: False. Actually, fora function with a default parameter value, the compiler supplies the defaultvalue in afunction call whenyoudo not explicitly provide an argument for the correspondingparameter.

Section 5 11 Passing Arguments by Value or by Reference

5.37 Swift allows youto pass arguments to functions byvalue or by

ANS: reference

5.38 When anargument ispassed by ,thecaller givesthefunctiontheability toaccess and modify the caller’soriginal variable.

ANS: reference

5.39 (True/False) Reference-type variables store references to objects, so specifying a referencetype variable as an argument passes the function a copyof the reference that refers to the object Even though the reference itself is passed byvalue, the function canstill use the reference it receives to interactwith andpossiblymodify the original object

ANS: True.

5.40 Applying keyword to a parameter declaration allows youto pass a variable to a function byreference the called function will beable to modify the original variable in the caller

ANS: inout

5.41 (True/False) Afunctioncan usemultiple inout parameters asanotherway to “return” multiplevalues to a caller.

ANS: True

5.42 (True/False) When an Int parameter is preceded with inout, this indicates that the argument passed to this method must be an Int and that it will be passed byreference

ANS: True

Section 5.12 Recursion

5.43 A function calls itself, eitherdirectly or indirectly through another function.

ANS: recursive

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Exercises 5

6 Chapter 5 Functions and Methods: ADeeper Look; enums and Tuples

Section 5 13 Nested Functions

5.44 (True/False) If necessary, an enclosing function can return a nested function sothat it can becalledfrom otherscopes forexample, you could define afunctionthat returns anested function based on a value passed to the enclosing function (as we do in this section’s example).

ANS: True.

5.45 (True/False) Eachfunction you define has a type that’s determinedby the types of its parameters and byits return type.

ANS: True

5.46 Because every function has a , you can assign functions to variables, pass them to functions and methods,and return them fromfunctions and methods

ANS: type

Short-Answer Exercises

Section 5.1 Introduction

5.1 Swift uses to package related software components forreuse.

ANS: modules

5.2 We use types forcreating named constants that improve codereadability.

ANS: enum

5.3 arecollections of values of the same or different types.

ANS: Tuples

5.4 (True/False) Both functionsand methods canbe overloaded.

ANS: True

5.5 (True/False) Bydefault, methods require allof theirarguments to belabeledwith parameter names.

ANS: False Actually, bydefault,methods require their second and subsequent arguments to be labeled with parameter names.

5.6 (True/False) Recursivefunctions callthemselves

ANS: True

Section 5.2 Modules in Swift

5.7 (True/False) Protocols aresimilar to classes in other languages

ANS: False Actually, protocolsare similarto interfaces in other languages

5.8 (True/False) A Dictionary maps keysto unique values.

ANS: False. Actually, a Dictionary maps unique keys to values

5.9 (True/False) Any itemthat is Printable has a toString property that returns a String representation ofthe item

ANS: False Actually, anyitem that is Printable has a description property that returns a String representation of the item.

5.10 (True/False) When you create a Swift project,Xcode places allof the project’s Swift code in a modulewith the same nameasyourproject.

ANS: True

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Section 5 3 Darwin Module Using Predefined C Functions

5.11 (True/False)The Darwin module provides access to the C libraries in Darwin Apple’s open-source UNIX-based core on whichthe OS Xand iOS operating systemsarebuilt

ANS: True

5.12 (True/False) The Darwin module is imported by default into several Cocoa and Cocoa Touch frameworks such asFoundation,AppKit and UIKit so that various software components in thoseframeworks caninteractwith the underlying operating system

ANS: True.

Section 5.4 Multiple-Parameter Function Definition

5.13 There must be one argumentin the function call foreach in the function definition.

ANS: parameter

5.14 (True/False) Parameters arevariables bydefault.

ANS: False Parameters are constants by default if you need to modify a parameter’s value in the function’s body, you must place var beforethe parameter’s name

5.15 (True/False) If the function returns a result, the statement return expression evaluates the expression, then returns the result (and control)to the caller.

ANS: True

Section 5 5 Random-Number Generation

5.16 (True/False) The arc4random_uniform function (a C-based UNIX function from the Darwin module) produces randomunsigned 32-bit integers (UInt32) from0 up to but not including an upper bound that youspecify as an argument

ANS: True

Section 5 6 1 Introducing Enumeration (enum) Types

5.17 (True/False) Like enums in otherC-based programming languages,a Swift enum ’sconstants have values bydefault.

ANS: False Actually, unlike enums in other C-based programming languages, a Swift enum ’s constants do not have values by default the constants themselves are the values

5.18 The raw typecanbe anyofSwift’s numerictypes, type String or type

ANS: Character

5.19 The ofan enum ’s constants must be unique

ANS: raw values

Section 5.6.2 Tuples and Multiple Function Return Values

5.20 (True/False) You must specifynames foreach element ofatuple.

ANS: False You’re not required to specify names for eachelement of a tuple, but doing so makes the codemore readable.

5.21 What does the following statementdo?

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved. Short-Answer Exercises 7

8 Chapter 5 Functions and Methods: ADeeper Look; enums and Tuples

let (die1, die2, sum) = rollDice()

ANS: This statement decomposes the tuple returned bythe function rollDice() it assigns the three values in the tuple to the constants die1, die2 and sum, respectively.

5.22 (True/False) Swift allows implicitconversions between numerictypes.

ANS: False Actually, unlike many other programming languages, Swift does not allow implicit conversions betweennumeric types.

5.23 What is the purpose of Int as used in the following statement?

let die1 = Int(1 + arc4random_uniform(6)) // first die roll

ANS: The random numbers returned byfunction arc4random_uniform are of type UInt. To convert these to type Int, you must use an Int cast as in this statement The castcreates a temporary Int copyof the argument in parentheses

Section 5.6.4 Accessing the Raw Value of an enum Constant

5.24 (True/False) Swift does not provide implicitconversions between enum constants and numeric types.

ANS: True

Section 5 7 Scope of Declarations

5.25 The ofadeclaration isthe portion ofthe code that canrefer to the declared entitybyits unqualified name.

ANS: scope

5.26 If a local variable, constantor parameter in a method hasthe same nameas a propertyof a class, the property ishidden until .

ANS: the blockterminates

Section 5 8 Function and Method Overloading

5.27 (True/False) Although overloaded functions (ormethods)have the same nameand similar parameter lists and bodies, youcanthink ofthem simply asdifferent functions (or methods)

ANS: True

5.28 Swift’s feature provides amechanism for writing asingle“genericfunction” that canperform the same tasks as an entiresetof overloaded functions.

ANS: generics

5.29 (True/False) The compiler considers the following twofunction headers to be identical:

func someFunction(a: Int, b: Double)

func someFunction(a: Double, b: Int)

ANS: False Actually, the order of the parameter types is important the compiler considers the precedingtwo functions to be distinct.

5.30 (True/False) Overloaded functions canhave the same or different return types ifthe functions have identical parameter lists.

ANS: False Actually, overloaded functions can have the sameor different return typesif the functions have different parameter lists

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Short-Answer Exercises 9

Section 5.9 External Parameter Names

5.31 (True/False) Bydefault, the parameter names you specifyin afunctiondefinition are global to that function they’re usedonlyin the bodyof that function to access the function’s argument values

ANS: False Actually, bydefault,the parameternames youspecify in afunction definition are local to that function they’re usedonlyin the bodyof that function to access the function’s argument values.

5.32 (True/False) You use ! to expose a local parameter nameasthe external parameter name.

ANS: False. Actually, you use# to expose a local parameter name asthe externalparameter name.

5.33 Once you exposean externalparameter name,you must provide an argument labelconsistingofthe corresponding ; otherwise, a compilation erroroccurs.

ANS: parameter name and a :

5.34 (True/False) In Objective-C, method calls readlike sentences. The method name refers to the firstparameter, and each subsequent parameter has aname that’s specified aspart ofthe method call In addition, method and parameter names often include prepositions to help make function calls readlike sentences

ANS: True

5.35 Properly namedfunctions enable function calls to readlike sentences. Forthe function func raiseBase(base: Int, #toExponent: Int) -> Int we couldcall the function as follows:

raiseBase(10, toExponent: 2) which reads like the sentence,

ANS: “Raise the base10 to the exponent 2 ”

Section 5 10 Default Parameter Values

5.36 Methods can have parameters that allow the caller to vary the number of arguments to pass

ANS: default

5.37 A function’s default parameter names are automatically parameter names when you providean argument for a defaultparameter,you must specify the defaultparameter’s namewith that argumentin the function call.

ANS: external

Section 5 11 Passing Arguments by Value or by Reference

5.38 (True/False) When an argumentis passed byvalue (the default forvalue types in Swift), a pointer to its value is passed to the calledfunction

ANS: False Actually, when an argument ispassed byvalue (the defaultforvalue typesin Swift),a copy of its value is made and passedto the called function.

5.39 You pass arguments by reference by declaring the parameter as inout and providing before the corresponding argumentin a function call.

ANS: &

5.40 (True/False) To pass an objectof a class typebyreference into a function, simply provide as anargument in thefunctioncall the variable that refers to the object Then, in thefunctionbody,

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

10 Chapter 5 Functions and Methods:ADeeper Look; enums and Tuples

reference the object using the parameter name The parameter refersto the original object in memory,sothe called function canaccess the original object directly

ANS: True

5.41 (True/False) When returning information from afunctionviaa return statement, thefunction returns a copy of the value storedin a value-type variable or a copy of the reference stored in a reference-type variable

ANS: True

5.42 (True/False) It’s a compilation errorto pass a variable to an inout parameter.

ANS: False Actually, It’s a compilation error to passa constant to an inout parameter.

5.43 When youpass a reference typevariable byreference, whathappens if youmodify it?

ANS: It willpoint to a new object.

5.44 (True/False) By default, value types arepassed byvalue. Objects of reference types arenot passed to methods; rather, references to objects arepassed to methods. The references themselves arepassed byvalue When a method receives a reference to an object,the method can manipulate the object directly, but the reference value cannot be changed to refer to a newobject

ANS: True

Section 5 12 Recursion

5.45 What does the following code do in a factorial function?

return number * factorial(number - 1)

ANS: It implements the recursionstep, makingarecursive call to factorial with a smaller value This recursionwilleventually reachthe basecase and terminate

Section 5 13 Nested Functions

5.46 (True/False) Ratherthan defining at global scope a utility(helper) function that’s called by onlyone other function, you can nest the utilityfunction’s definitionin the scope of the function that uses it This hides it from the rest of your code For example, an array-sorting function could define a nested swap functionforswapping elements into sortedorder.

ANS: True

5.47 (True/False) Anested function also has access to the local variables and constants in its enclosing function’s scope, including the enclosing function’s parameters

ANS: True

5.48 What does the following function typespecify?

(Int, Int) -> Bool

ANS: The parenthesizedlist (Int, Int) includesthe functions parameter types;the arrow notation -> Bool specifies the function’s return type

5.49 Once you’ve assigned a function to a variable, youcan use the variable to

ANS: callthe function

Programming Exercises

5.1 (Rounding Numbers) To round numbers to specific decimal places, use a statementlike

y = floor(x * 10 + 0.5) / 10; which rounds x to the tenths position(i e.,the first positionto the right ofthe decimal point), or

y = floor(x * 100 + 0.5) / 100;

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Programming Exercises 11

which rounds x to the hundredths position (i.e., the secondposition to the right of the decimal point) Definefourfunctions forrounding a number x in various ways:

a) roundToInteger(number)

b) roundToTenths(number)

c) roundToHundredths(number)

d) roundToThousandths(number)

Write a programthat tests the four functions For each value, display the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.

5.2 (Rounding Numbers) Repeat Exercise 5 1 using one function named round that returns a tuple containing the original value and the fourrounded results.

5.3 (Exponentiation) Write a function that’s called as follows

raiseBase(base, toPower: exponent) and returns the value of base raised to the exponent power For example, the call

raiseBase(3, toPower: 4) calculates 34 (or 3 * 3 * 3 * 3) Assume that exponent is a positive, nonzero integer and that base is an integer.Use a loop to performthe calculation. Incorporate this function into a program that performexponentiation calculations

© 2016Pearson Education, Inc., Hoboken, NJ. All rights reserved.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.
Java how to program late objects 10th edition deitel solutions manual 1 by mary.larson317 - Issuu