Chapter 4 includes four Twist in the Tale exercises.
Purpose: To remind you to be careful with the overloaded methods of the class String that accept either char or String or both, the code in this exercise passes an invalid method argument—a char—to method startsWith.
Answer: e
Explanation: When it comes to the String class, it’s easy to confuse the methods that accept char or String values as method arguments. For example, the overloaded method indexOf can accept both String and char values to search for a target value in a String. The methods startsWith and endsWith accept only arguments of type String. The method charAt accepts only method arguments of type int. Hence, this method can be passed char values, which are stored as unsigned integer values.
Purpose: This exercise has multiple purposes:
Answer: d
Explanation: The correct way to create an object of class StringBuilder with a default capacity of 16 characters is to call StringBuilder’s no-argument constructor, as follows:
StringBuilder name = StringBuilder();
Purpose: Identify the difference between an array element that isn’t initialized and an array element that doesn’t exist. A pictorial representation of a multidimensional array is quick to draw, and you can easily refer to its nonexistent or null array elements. This concept is shown in figure A.3.
Answer: b, d
Explanation: Option (a) is incorrect. Initializing a row of array multiStrArr with {"Jan","Feb",null} and {"Jan","Feb",null,null} isn’t the same. The former option defines three array elements with the last array element assigned to null. The latter option defines four array elements with the last two array elements assigned to null.
Option (b) is correct. The array element at the position exists but isn’t assigned any value. It’s assigned to null.
Option (c) is incorrect. Because multiStrArr[1] refers to null, multiStrArr[1][1] doesn’t exist.
Option (d) is correct. As shown in figure A.3, the array multiStrArr doesn’t define an equal number of elements in each row, so it’s asymmetric.
Purpose: This exercise tries to trick you by using multiple objects of ArrayList, assigning the object reference of one ArrayList to another, and modifying the value of the ArrayList objects. String objects are immutable—you can’t change their values.
Answer: a
Explanation: Option (a) is correct, and options (b), (c), and (d) are incorrect. The ArrayLists myArrList and yourArrList contain String objects. The value of String objects can’t be modified once created.
3.133.141.219