4.10. Answers to sample exam questions

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]);
    }
}

  1. 4c010
  2. 4c10
  3. 113
  4. 103
  5. Compilation error

Answer: e

Explanation: The code in this question won’t compile due to

arr[3] = longVar;

The preceding line of code tries to assign a value of type long to a variable of type int. Because Java doesn’t support implicit narrowing conversions (for example, long to int in this case), the assignment fails. Also, this 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 8 Java Programmer I exam, be careful about such tactics. If any of the answers lists 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 a compilation error.

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]);
    }
}

  1. 0:0
  2. a:b
  3. 0:b
  4. a:0
  5. 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-3.

Which of the following are valid lines of code to define a multidimensional int array?

  1. int[][] array1 = {{1, 2, 3}, {}, {1, 2,3, 4, 5}};
  2. int[][] array2 = new array() {{1, 2, 3}, {}, {1, 2,3, 4, 5}};
  3. int[][] array3 = {1, 2, 3}, {0}, {1, 2,3, 4, 5};
  4. int[][] array4 = 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 the code in option (a).

Q4-4.

Which of the following statements are correct?

  1. The following code executes without an error or exception:

    ArrayList<Long> lst = new ArrayList<>();
    lst.add(10);
  2. Because ArrayList stores only objects, you can’t pass element of an ArrayList to a switch construct.
  3. Calling clear() or remove() on an ArrayList will remove all its elements.
  4. If you frequently add elements to an ArrayList, specifying a larger capacity will improve the code efficiency.
  5. 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. The default type of a non-floating numeric literal value is int. You can’t add an int to an ArrayList of type Long. You can pass values of type Long or long to its add method.

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 clear() 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 Array-List 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-5.

Which of the following statements are correct?

  1. An ArrayList offers a resizable array, which is easily managed using the methods it provides. You can add and remove elements from an ArrayList.
  2. Values stored by an ArrayList can be modified.
  3. You can iterate through elements of an ArrayList using a for loop, Iterator, or ListIterator.
  4. An ArrayList requires you to specify the total elements before you can store any elements in it.
  5. 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-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

  1. Line 7 prints true.
  2. Line 7 prints false.
  3. Line 8 prints -1.
  4. Line 8 prints 1.
  5. Line 9 removes all elements of the list ejg.
  6. Line 9 sets ejg to null.
  7. Line 10 prints null.
  8. Line 10 prints [].
  9. Line 10 prints a value similar to ArrayList@16356.
  10. Line 11 throws an exception.
  11. Line 11 prints null.

Answer: a, d, e, h, j

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 the 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-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);
    }
}

  1. true printed once
  2. false printed once
  3. true printed in an infinite loop
  4. 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-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);
    }
}

  1. gZmeAZ
  2. gZmeAa
  3. gZm
  4. gZ
  5. 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 modify the object’s own value. They all create and return new String objects.

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);
    }
}

  1. gZmeAZ
  2. gZmeAa
  3. gZm
  4. gZ
  5. game

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-10.

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);
    }
}

  1. 12S512S5
  2. 12S12S
  3. 1025102S
  4. Runtime exception

Answer: a

Explanation: This question tests 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-11.

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);
    }
}

  1. 521
  2. Runtime exception
  3. 65321
  4. 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-12.

What is the output of the following code?

String printDate = LocalDate.parse("2057-08-11")
                      .format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(printDate);

  1. August 11, 2057T00:00
  2. Saturday Aug 11,2057T00:00
  3. 08-11-2057T00:00:00
  4. Compilation error
  5. Runtime exception

Answer: e

Explanation: The example code in this question calls LocalDate.parse(), passing it a string value but no DateTimeFormatter instance. In this case, the text 2057-08-11 is parsed using DateTimeFormatter.ISO_LOCAL_DATE. LocalDate.parse() returns a LocalDate instance.

The example code then calls the format method on a LocalDate instance, using DateTimeFormatter.ISO_DATE_TIME. The code compiles successfully because the format method accepts a DateTimeFormatter instance. But format() throws an exception at runtime because it tries to format a LocalDate instance using a formatter (ISO_DATE_TIME) that defines rules for a date/time object. When no matching time values are found in a LocalDate object, an exception is thrown.

Exam Tip

The parse method is defined as a static method in classes LocalDate, LocalTime, and LocalDateTime. The class DateTimeFormatter defines the method parse as an instance method. But format() is defined as an instance method by all. The example code wouldn’t have compiled if the order of calling parse() and format() was reversed:

String printDate = LocalDate.format(DateTimeFormatter.ISO_DATE_TIME)
                      .parse("2057-08-11");

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.70