Skip to content
Textbook Guides

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.

Preview 16 of 65 pages

See the first 16 pages exactly as they appear in the document.

  1. Page 1
    Read page 1 as text

    Answers to review questions from Chapter 1 1. When you write a Java program, do you prepare a source file or a class file? A source file 2. What characters are used to mark comments in a Java program? /* . . . */ 3. What is the significance of each component in the package declaration package edu.stanford.cs.javacs2.ch1; edu indicates the educational domain stanford indicates Stanford University cs indicates the Computer Science department javacs1 indicates that this package goes with the Java book for CS1 ch1 indicates that this package is associated with Chapter 1 4. How would you define a constant called CENTIMETERS_PER_INCH with the value 2.54? public static final double CENTIMETERS_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 named main 6. What is meant by the term boilerplate? What is the boilerplate form of the main method used throughout this book? Boilerplate refers to idiomatic programming patterns that are repeated in different programs but have no real significance for the programmer. The boilerplate form of main is public static void main(String[] args) { new classname ().run(); } 7. Indicate which of the following are legal variable names in Java: a. x Legal b. formula1 Legal c. average_rainfall Legal d. %correct Illegal (begins with % ) e. short Illegal (reserved word) f. tiny Legal g. total output Illegal (contains a space) h. aVeryLongVariableName Legal i. 12MonthTotal Illegal (begins with a digit) j. marginal-cost Illegal (contains a hyphen) k. b4hand Legal (but perhaps too clever) l. _stk_depth Legal 8. What are the two attributes that define a data type? Types are defined by a domain and a set of operations.

  2. Page 2
  3. Page 3
    Read page 3 as text

    9. What sizes does Java assign to the types byte , short , int , and long ? byte = 8 bits short = 16 bits int = 32 bits long = 64 bits 10. What coding system does Java use for characters? Unicode 11. What does ASCII stand for? What relationship does the ASCII code have to the code used to represent characters in Java? American Standard Code for Information Interchange The ASCII code matches the first 256 characters in the Unicode standard. 12. List all possible values of type boolean . false and true 13. What statements would you include in a program to read a value from the user and store it in the variable x , which is declared as a double ? You would first need to declare a scanner using Scanner scanner = new Scanner(System.in); Later in the program you could read the value of x using lines like this: System.out.print("Enter x: "); double x = scanner.nextDouble(); 14. Indicate the values and types of the following expressions: a. 2 + 3 5 ( int ) b. 19 / 5 3 ( int ) c. 19.0 / 5 3.8 ( double ) d. 3 * 6.0 18.0 ( double ) e. 19 % 5 4 ( int ) f. 2 % 7 2 ( 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 . The subtraction operator is written between two operands as in x - 2. 16. Calculate the result of each of the following expressions: a. 6 + 5 / 4 - 3 4 b. 2 + 2 * (2 * 2 - 2) % 2 / 2 2 c. 10 + 9 * ((8 + 7) % 6) + 5 * 4 % 3 * 2 + 1 42 d. 1 + 2 + (3 + 4) * ((5 * 6 % 7 * 8) - 9) - 10 42

  4. Page 4
    Read page 4 as text

    17. What does the term truncation mean? Truncation converts a floating-point number to an integer by throwing away any digits after the decimal point. Thus, the floating-point number 3.9999 truncates to the integer 3. 18. What is a type cast and how do you indicate one in Java? A type cast is used to indicate conversion of one type to another. In Java, type casts are written by enclosing the type name in parentheses before the value to be converted, as in the expression (int) x , which truncates x to 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 sign used for assignment, as in balance += deposit; 20. What is the difference between the expressions ++x and x++ ? Both expressions increment (add one to) the value of x . The difference is the value of the expression. The expression ++x returns the incremented value; the expression x++ returns the original value before the increment. 21. What is meant by short-circuit evaluation? Short-circuit evaluation evaluates only as much of an expression as is necessary to determine the result. 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 is true . 22. Write out the general syntactic form for each of the following control statements: if , switch , while , and for . if ( condition ) statement if ( condition ) statement else statement switch ( e ) { case c 1 : statements break; case c 2 : statements break; . . . more case clauses . . . default: statements break; } while ( conditional-expression ) { statements } for ( init ; test ; step ) { statements }

  5. Page 5
    Read page 5 as text

    23. Describe in English the operation of the switch statement, including the role of the break statement at the end of each case clause. When the program executes a switch statement, it evaluates the control expression and compares it against the values c 1 , c 2 , and so forth, each of which must be a constant. If one of the constants matches the value of the control expression, the statements in the associated case clause are executed. When the program reaches the break statement at the end of the clause, the operations specified by that clause are complete, and the program continues with the statement that follows the entire switch statement. If none of the expression match the value of the control expression, the program executes the statements in the default clause, if any. 24. What is a sentinel? What is the general form of the read-until-sentinel pattern? A sentinel is a value used to indicate some kind of special processing and often signals the end of a list of input values. 25. What for loop control line would you use in each of the following situations? a. Counting from 1 to 100 for (int i = 1; i <= 100; i++) b. Counting by sevens starting at 0 until the number has more than two digits for (int i = 0; i < 100; i += 7) c. Counting backward by twos from 100 to 0 for (int i = 100; i >= 0; i -= 2) 26. Define each of the following terms: class, object, method, instance variable, subclass, and superclass. A class is a template for data objects that share a common representation and set of operations. An object is a data value that is an instance of a particular class. A method is a sequence of program steps that have been collected together and given a name. An instance variable is a particular data value stored within an object. A subclass is a class that extends the behavior of an existing class, which becomes its superclass. 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 class Arthropoda? The direct subclasses are Crustacea, Insecta, and Arachnida. The descendents of Insecta ( Hymenoptera, Formicidae, Lasius, and niger ) are indirect subclasses of Arthropoda. 29. What two features does this chapter identify as the most important aspects of the object-oriented programming model? Encapsulation and inheritance.

  6. Page 6
    Read page 6 as text

    Answers to review questions from Chapter 2 1. Explain in your own words the difference between a method and a program . A method computes a value or performs some operation on behalf of the code for a program. A program executes 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 as calling that method. In the process of making a call, the caller can provide data to the method in the form of arguments, which are a set of local variables that are initialized from the values written inside the parentheses that designate the call. When the method completes its work, it returns to its caller, often passing back a value as a result. 3. Can there be more than one return statement in the body of a method? Yes. A method can include any number of return statements. 4. What is a static method? A static method is a method associated with a class rather than with a specific object. Static methods 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 the Math class? Math.sin(Math.toRadians(45)) 6. What is a predicate method? A predicate method is a method that returns a Boolean value. 7. Describe the difference in role between an implementer and a client. The implementer is responsible for writing the actual code that carries out an operation. The client invokes that code to perform the operation but need not understand the details for doing so. 8. What is meant by the term overloading? How does the Java compiler use signatures to implement overloading? In Java, the term overloading refers to the fact that you can define several different methods with the same name, as long as each method has a different signature, which indicates the number and types of the arguments. When the Java compiler sees a call to an overloaded method with a particular name, it examines the argument values to see which version of that method is required. 9. What is a stack frame? A stack frame is the region of memory used to hold the values of local variables during a method call. The frame is created when the method is called and deleted when the method returns.

  7. Page 7
    Read page 7 as text

    10. Describe the process by which arguments are associated with parameters. Arguments and parameters are matched by their order in the argument list. The names of the parameters have no bearing on the association process. 11. Variables declared within a method are said to be local variables . What is the significance of the word local in this context? Local variables can be used only within that method. Neither the caller nor any method called from inside a method has access to those local variables. 12. What is the difference between iteration and recursion? Iteration refers to the process of performing repeated calculations by using a loop to execute the same code. 13. What is meant by the phrase recursive leap of faith? Why is this concept important to you as a programmer? The recursive leap of faith refers to the idea that, in writing a recursive solution, you can assume that smaller instances of the problem work and then reassemble those solutions to solve the original problem. If you fail to adopt the recursive leap of faith, you are forced to trace the operation of the program all the way down to the simple cases, which often makes the process too complex to follow. 14. In the section entitled “Tracing the recursive process,” the text goes through a long analysis of what happens internally when fact(4) is called. Using this section as a model, trace the execution of fib(3) , sketching out each stack frame created in the process. Step 1: Step 2: Step 3:

  8. Page 8
    Read page 8 as text

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

  9. Page 9
    Read page 9 as text

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

  10. Page 10
    Read page 10 as text

    15. What is a recurrence relation? A recurrence relation is an expression defining each new element of a sequence in terms of earlier elements. 16. Modify Fibonacci’s rabbit problem by introducing the additional rule that rabbit pairs stop reproducing after giving birth to three litters. How does this assumption change the recurrence relation? What changes do you need to make in the simple cases? The new recurrence relation must subtract out the rabbits that are too old to reproduce, which are all of those born more than four months ago. The recurrence relation therefore looks like this: t n = t n - 1 + t n - 2 – t n - 5 The simple case must now take account of the fact that the value of n may now range into negative territory, when there were no rabbits. The code for the revised rabbit problem looks like this: private int rabbits(int n) { if (n <= 0) { return 0; } else if (n == 1) { return 1; } else { return rabbits(n - 1) + rabbits(n - 2) - rabbits(n - 5); } } 17. How many times is fib(1) called when fib(n) is calculated using the recursive implementation given in Figure 2-5? The method fib(1) is called fib(n) times. 18. What is a wrapper method? Why are wrapper methods often useful in writing recursive methods? A wrapper method is a method whose only role is to set things up for a call to a more general recursive method that does all the work. In many situations, the recursive process requires additional state information that the wrapper method can provide. 19. What would happen if you eliminated the if (n == 1) check from the method additiveSequence , so that the implementation looked like this: int additiveSequence(int n, int t0, int t1) { if (n == 0) return t0; return additiveSequence(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 with 0 as the first argument and the value of t1 as the second. Since n will then be 0 in the recursive call, the method will return the original value of t1 , just as before.

  11. Page 11
    Read page 11 as text

    Answers to review questions from Chapter 3 1. What is the difference between a character and a string? A character is a data value that represents a single character of text. A string is a sequence of characters. 2. True or false: In Java, you can determine the length of the string stored in the variable str by calling length(str) . False. You need to call str.length() . 3. What does it mean to say that the String class is immutable? An immutable class has the property that the value of an object cannot be changed after it is created. Strings in Java are immutable, which means that none of the methods in the String class ever changes a string; string methods instead return a new string containing the updated value. 4. If you call s1.concat(s2) , which string is the receiver? The s1 string is the receiver. 5. What is the effect of the + operator when it is used with two string operands? What happens if one operand 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 either argument is a string. If only one argument is a string, Java converts the other to its string representation. 6. True or false: The index positions in a string begin at 0 and extend up to the length of the string minus 1. True. 7. What are the arguments to the substring method? What happens if you omit the second argument? The arguments to substring are the first index position of the desired substring and the index of the position immediately following the desired substring. If you omit the second argument, substring returns a substring that extends through the end of the string. 8. What is lexicographic ordering? Lexicographic ordering is similar to alphabetical ordering but uses the ordering imposed by the underlying 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 are identical (i.e., whether they are the same object) rather than whether they contain the same characters.

  12. Page 12
    Read page 12 as text

    10. Describe how the compareTo method uses the return value to indicate the relative ordering of two strings. The compareTo method returns 0 if the strings are equal, a positive value if the receiver string is greater than the argument, and a negative value if the receiver string is smaller than the argument. 11. What value does indexOf return if the pattern string does not appear? The sentinel value − 1. 12. What is the significance of the optional second argument to indexOf ? The second argument represents the starting position for the search. 13. What effect does the following statement have on the value of str ? str.trim() The trim method returns a copy of the original string after removing any leading or trailing whitespace characters. As written, however, the receiver string str is unaffected. 14. What is the correct way to achieve the effect clearly intended by the expression in the preceding question? str = str.trim(); 15. Suppose that you have declared and initialized the variable s as follows: String s = "hello, world"; Given that declaration, what is the value of each of the following calls: a. s + '!' "hello, world!" b. s.length() 12 c. s.charAt(5) ',' d. s.indexOf('l') 2 e. s.indexOf("l", 5) 10 f. 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 to compareTo , simply indicate the sign of the result.) a. "ABC".equals("abc") false b. "ABC".equalsIgnoreCase("abc") true c. "ABC".compareTo("ABC") 0 d. "ABC".compareTo("AB") + e. "ABC".compareTo("abc") – f. "ABC".endsWith("c") false

  13. Page 13
    Read page 13 as text

    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 reverse order, starting with the last character and ending with the first? for (int i = 0; i < str.length(); i++) { . . . body of loop that uses the character str.charAt(i) . . . } 19. What is the pattern for growing a string through concatenation? String str = ""; 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 the Character class: a. Character.isDigit(7) false b. Character.isDigit('7') true c. Character.isLetter('7') false d. Character.toUpperCase(7) 7 e. Character.toUpperCase('A') 'A' f. Character.toLowerCase('A') 'a'

  14. Page 14
    Read page 14 as text

    Answers to review questions from Chapter 4 1. What are the principal differences between a text file and a string? The two main differences are (1) the information stored in a file is permanent and (2) files are usually 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 an exception? An exception is an unusual condition outside the normal program flow. . 4. What is the general form of the try statement? try { Block of code in which the exception can be caught. } catch ( type var ) { Code to respond to an exception of the specified type. } . . . other catch clauses if necessary . . . 5. True or false: Catching the IOException raised by the classes in the java.io package is optional. False. Java programs must catch these exceptions. 6. Suppose that you have a string variable filename that contains the name of a text file. What statements would you write to create a reader variable named rd that you could then use to read lines from this file? BufferedReader rd = new BufferedReader(new FileReader(rd)); 7. Why does the read method return an int rather than a char ? The read must be able to signal the end of the file, which is represented by the integer − 1. That value needs to be outside the character range, because the file could contain any combination of characters. 8. How do you detect the end of a file if you are using readLine to read it line by line? The readLine method returns null as a sentinel value. 9. What three writer classes are typically involved in opening a text file for output? FileWriter , BufferedWriter , and PrintWriter . 10. True or false: Java 5.0 reintroduced the printf method, which was originally designed for the programming language C. True. 11. What is a format code? A format code is a sequence of characters beginning with a percent sign and ending with a key letter that specifies how printf should format a value.

  15. Page 15
    Read page 15 as text

    12. How do you include a percent sign in a printf format string? Use two consecutive percent signs. 13. In your own words, describe the differences between the %e , %f , and %g format codes. The %e format code always displays its value using scientific notation with the letter e preceding the power of ten used as the exponent. The %f format code always displays its value as a floating-point value without an exponent. The %g format code uses either scientific notation or floating-point conversion, whichever produces the most compact result. 14. What is the difference in the output produced by the %e and %E format codes? The %e format code uses a lowercase e to signify the exponent in scientific notation. The %E format code uses an uppercase E . 15. The constant PI in the java.lang.Math class is defined as public static final double PI = 3.141592653589793238; What printf format 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? The Scanner class. 17. What do the letters in the file type .csv stand for? Comma-separated values. 18. What call would you invoke on a Scanner object to read .csv files? scanner.useDelimiter(","); 19. What Java class makes it possible to open files using an interactive dialog? The JFileChooser class. 20. What is the purpose of a throws clause in a method definition? The throws clause indicates to the Java compiler that this method may throw the specified exceptions.

  16. Page 16
    Read page 16 as text

    Answers to review questions from Chapter 5 1. What are the two characteristic properties of an array? An array is (1) ordered and (2) homogeneous. 2. Define the following terms: element, index, element type, array length, and selection. An element is the value in a particular position in the array. An index is the integer that identifies the position number, which start at 0 in Java. The element type is the type of each element, which must all be the same. The array length is the number of elements in the array. Selection is the process of choosing a particular element by its index. 3. Write declarations that create and initialize the following array variables: a) An array doubleArray consisting of 100 values of type double double[] doubleArray = new double[100]; b) An array inUse consisting of 16 values of type boolean boolean[] inUse = new boolean[100]; c) An array lines consisting of 50 strings String[] lines = new String[50]; 4. How do you determine the length of an array? By selecting its length field, as in array.length . 5. The code for the GymnasticsJudge program uses the following statement to prompt the user to enter each judge’s score: System.out.print("Enter score for judge " + (i + 1) + ": "); What is the reason behind adding 1 to the value of i ? Adding one to the index transforms it from the 0-based index scheme that Java uses to the more familiar style of numbering that starts at 1 . 6. In the code shown for the preceding exercise, are the parentheses around the expression i + 1 necessary? Why or why not? The parentheses are necessary. Without them, the prompt string would start with the string "Enter score for judge " followed by the value of i , the digit 1, and a colon. 7. Define the following terms: bit, byte, and word. A bit is a data value with exactly two states, typically denoted by 0 and 1 . A byte is a combined sequence of eight bits that can take on values between 0 and 255; a byte is also the smallest addressable unit in memory. A word is a longer collection of bits that represents the natural size for an integer in the hardware of the machine. 8. What is the etymology of the word bit? The word bit first appeared in a publication by Claude Shannon as a contraction of binary digit .

49 more pages in the full document

Unlock it once and it stays in your library, ready to chat with or turn into flashcards.

Unlock the full document
See all

Study this document with CramX

Once it is in your library, every tool can work from it.