Chapter 4 Strings, Arrays

Ace your homework & exams now with Quizwiz!

What is the output of the following code? class EJavaGuruStringBuilder { public static void main(String args[]) { StringBuilder ejg = new StringBuilder(10 + 2 + "SUN" + 4 + 5); ejg.append(ejg.delete(3, 6)); System.out.println(ejg); } } a) 12S512S5 b) 12S12S c) 1025102S d) dRuntime exception

Answer: a Explanation: This question tests you on your understanding of operators, String, and StringBuilder. The following line of code returns 12SUN45: 10 + 2 + "SUN" + 4 + 5 The + operator adds two numbers but concatenates the last two numbers. When the + operator encounters a String object, it treats all the remaining operands as String objects. Unlike the String objects, StringBuilder objects are mutable. The append and delete methods defined in this class change its value. ejg.delete(3, 6) modifies the existing value of the StringBuilder to 12S5. It then appends the same value to itself when calling ejg.append(), resulting in the value 12S512S5.

Q4-7. What is the output of the following code? class EJavaGuruString { public static void main(String args[]) { String ejg1 = new String("E Java"); String ejg2 = new String("E Java"); String ejg3 = "E Java"; String ejg4 = "E Java"; do System.out.println(ejg1.equals(ejg2)); while (ejg3 == ejg4); } } a) true printed once b) false printed once c) true printed in an infinite loop d) false printed in an infinite loop

Answer: c Explanation: String objects that are created without using the new operator are placed in a pool of Strings. Hence, the String object referred to by the variable ejg3 is placed in a pool of Strings. The variable ejg4 is also defined without using the new operator. Before Java creates another String object in the String pool for the variable ejg4, it looks for a String object with the same value in the pool. Because this value already exists in the pool, it makes the variable ejg4 refer to the same String object. This, in turn, makes the variables ejg3 and ejg4 refer to the same String objects. Hence, both of the following comparisons will return true: ■ ejg3 == ejg4 (compare the object references) ■ ejg3.equals(ejg4) (compare the object values) Even though the variables ejg1 and ejg2 refer to different String objects, they define the same values. So ejg1.equals(ejg2) also returns true. Because the loop condition (ejg3==ejg4) always returns true, the code prints true in an infinite loop.

Q4-5. Which of the following statements are correct? a) An ArrayList offers a resizable array, which is easily managed using the methods it provides. You can add and remove elements from an ArrayList. b) Values stored by an ArrayList can be modified. c) You can iterate through elements of an ArrayList using a for loop, Iterator, or ListIterator. d) An ArrayList requires you to specify the total elements before you can store any elements in it. e) An ArrayList can store any type of object.

Answer: a, b, c, e Explanation: Option (a) is correct. A developer may prefer using an ArrayList over an array because it offers all the benefits of an array and a list. For example, you can easily add or remove elements from an ArrayList. Option (b) is correct. Option (c) is correct. An ArrayList can be easily searched, sorted, and have its values compared using the methods provided by the Collection framework classes. Option (d) is incorrect. An array requires you to specify the total number of elements before you can add any element to it. But you don't need to specify the total number of elements that you may add to an ArrayList at any time in your code. Option (e) is correct.

Q4-3. Which of the following are valid lines of code to define a multidimensional int array? a) int[][] array1 = {{1, 2, 3}, {}, {1, 2,3, 4, 5}}; b) int[][] array2 = new array() {{1, 2, 3}, {}, {1, 2,3, 4, 5}}; c) int[][] array3 = {1, 2, 3}, {0}, {1, 2,3, 4, 5}; d) int[][] array5 = new int[2][];

Answer: a, d Explanation: Option (b) is incorrect. This line of code won't compile because new array() isn't valid code. Unlike objects of other classes, an array isn't initialized using the keyword new followed by the word array. When the keyword new is used to initialize an array, it's followed by the type of the array, not the word array. Option (c) is incorrect. To initialize a two-dimensional array, all of these values must be enclosed within another pair of curly braces, as shown in option (a).

Q4-6. What is the output of the following code? import java.util.*; // line 1 class EJavaGuruArrayList { // line 2 public static void main(String args[]) { // line 3 ArrayList<String> ejg = new ArrayList<>(); // line 4 ejg.add("One"); // line 5 ejg.add("Two"); // line 6 System.out.println(ejg.contains(new String("One"))); // line 7 System.out.println(ejg.indexOf("Two")); // line 8 ejg.clear(); // line 9 System.out.println(ejg); // line 10 System.out.println(ejg.get(1)); // line 11 } // line 12 } // line 13 a) Line 7 prints true b) Line 7 prints false c) Line 8 prints -1 d) Line 8 prints 1 e) Line 9 removes all elements of the list ejg f) Line 9 sets ejg to null g) Line 10 prints null h) Line 10 prints [] i) Line 10 prints a value similar to ArrayList@16356 k) Line 11 throws an exception l) Line 11 prints null

Answer: a, d, e, h, k Explanation: Line 7: The method contains accepts an object and compares it with the values stored in the list. It returns true if the method finds a match and false otherwise. This method uses the equals method defined by the object stored in the list. In the example, the ArrayList stores objects of class String, which has overridden the equals method. The equals method of the String class compares the values stored by it. This is why line 7 returns the value true. Line 8: indexOf returns the index position of an element if a match is found; otherwise, it returns -1. This method also uses the equals method behind the scenes to compare the values in an ArrayList. Because the equals method in class String compares its values and not the reference variables, the indexOf method finds a match in position 1. Line 9: The clear method removes all the individual elements of an ArrayList such that an attempt to access any of the earlier ArrayList elements will throw a runtime exception. It doesn't set the ArrayList reference variable to null. Line 10: ArrayList has overridden the toString method such that it returns a list of all its elements enclosed within square brackets. To print each element, the toString method is called to retrieve its String representation. Line 11: The clear method removes all the elements of an ArrayList. An attempt to access the (nonexistent) ArrayList element throws a runtime IndexOutOfBounds- Exception exception. This question tests your understanding of ArrayList and determining the equality of String objects.

Q4-8. What is the output of the following code? class EJavaGuruString2 { public static void main(String args[]) { String ejg = "game".replace('a', 'Z').trim().concat("Aa"); ejg.substring(0, 2); System.out.println(ejg); } } a) gZmeAZ b) gZmeAa c) gZm d) gZ e) game

Answer: b Explanation: When chained, methods are evaluated from left to right. The first method to execute is replace, not concat. Strings are immutable. Calling the method substring on the reference variable ejg doesn't change the contents of the variable ejg. It returns a String object that isn't referred to by any other variable in the code. In fact, none of the methods defined in the String class modifies the object's own value. They all create and return new String objects.

What is the output of the following code? class EJavaGuruStringBuilder2 { public static void main(String args[]) { StringBuilder sb1 = new StringBuilder("123456"); sb1.subSequence(2, 4); sb1.deleteCharAt(3); sb1.reverse(); System.out.println(sb1); } } a) 521 b) Runtime exception c) 65321 d) 65431

Answer: c Explanation: Like the method substring, the method subSequence doesn't modify the contents of a StringBuilder. Hence, the value of the variable sb1 remains 123456, even after the execution of the following line of code: sb1.subSequence(2, 4); The method deleteCharAt deletes a char value at position 3. Because the positions are zero-based, the digit 4 is deleted from the value 123456, resulting in 12356. The method reverse modifies the value of a StringBuilder by assigning to it the reverse representation of its value. The reverse of 12356 is 65321.

Q4-4. Which of the following statements are correct? a) By default, an ArrayList creates an array with an initial size of 16 to store its elements. b) Because ArrayList stores only objects, you can't pass element of an ArrayList to a switch construct. c) Calling clear() or remove() on an ArrayList, will remove all its elements. d) If you frequently add elements to an ArrayList, specifying a larger capacity will improve the code efficiency. e) Calling the method clone() on an ArrayList creates its shallow copy; that is, it doesn't clone the individual list elements.

Answer: d, e Explanation: Option (a) is incorrect. By default, an ArrayList creates an array with an initial size of 10 to store its elements. Option (b) is incorrect. Starting with Java 7, switch also accepts variables of type String. Because a String can be stored in an ArrayList, you can use elements of an ArrayList in a switch construct. Option (c) is incorrect. Only remove() will remove all elements of an ArrayList. Option (d) is correct. An ArrayList internally uses an array to store all its elements. Whenever you add an element to an ArrayList, it checks whether the array can accommodate the new value. If it can't, ArrayList creates a larger array, copies all the existing values to the new array, and then adds the new value at the end of the array. If you frequently add elements to an ArrayList, it makes sense to create an ArrayList with a bigger capacity because the previous process isn't repeated for each ArrayList insertion. Option (e) is correct. Calling clone() on an ArrayList will create a separate reference variable that stores the same number of elements as the ArrayList to be cloned. But each individual ArrayList element will refer to the same object; that is, the individual ArrayList elements aren't cloned.

Q4-2. What is the output of the following code? class EJavaGuruArray2 { public static void main(String args[]) { int[] arr1; int[] arr2 = new int[3]; char[] arr3 = {'a', 'b'}; arr1 = arr2; arr1 = arr3 System.out.println(arr1[0] + ":" + arr1[1]); } } a 0:0 b a:b c 0:b d a:0 e Compilation error

Answer: e Explanation: Because a char value can be assigned to an int value, you might assume that a char array can be assigned to an int array. But we're talking about arrays of int and char primitives, which aren't the same as a primitive int or char. Arrays themselves are reference variables, which refer to a collection of objects of similar type.

Q4-9. What is the output of the following code? class EJavaGuruString2 { public static void main(String args[]) { String ejg = "game"; ejg.replace('a', 'Z').trim().concat("Aa"); ejg.substring(0, 2); System.out.println(ejg); } } a) gZmeAZ b) gZmeAa c) gZm

Answer: e Explanation: String objects are immutable. It doesn't matter how many methods you execute on a String object; its value won't change. Variable ejg is initialized with the String value "game". This value won't change, and the code prints game.

Q4-1. What is the output of the following code? class EJavaGuruArray { public static void main(String args[]) { int[] arr = new int[5]; byte b = 4; char c = 'c'; long longVar = 10; arr[0] = b; arr[1] = c; arr[3] = longVar; System.out.println(arr[0] + arr[1] + arr[2] + arr[3]); } } a) 4c010 b) 4c10 c) 113 d) 103 e)Compilation error

Answer: e Explanation: The previous code won't compile due to the following line of code: arr[3] = longVar; This line of code tries to assign a value of type long to a variable of type int. Because Java does support implicit widening conversions for variables, the previous code fails to compile. Also, the previous code tries to trick you regarding your understanding of the following: ■ Assigning a char value to an int array element (arr[1] = c) ■ Adding a byte value to an int array element (arr[0] = b) ■ Whether an unassigned int array element is assigned a default value (arr[2]) ■ Whether arr[0] + arr[1] + arr[2] + arr[3] prints the sum of all these values, or a concatenated value When answering questions in the OCA Java SE 7 Java Programmer I exam, be careful about such tactics. If any of the answers list a compilation error or a runtime exception as an option, look for obvious lines of code that could result in it. In this example, arr[3] = longVar will result in compilation error.


Related study sets

Xcel Testing Solutions- Life and Health Insurance- Weighted Exam- 150 Questions

View Set

Criminal Courts & Procedures Chapter 7

View Set

HESI: Seizure Disorder and Rationale

View Set

Navar: Art 101 Ohlone College Midterm (Only sections 1, 2, 3 and 4)

View Set

Environmental Health Quiz 5 (Ch. 5)

View Set

NU144- Chapter 46: Management of Patients With Gastric and Duodenal Disorders

View Set