chapter 4 sample exam questions Flashcards

Selected classes from the Java API and array

1
Q
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
A

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 excep-tion 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
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
A

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 them-selves are reference variables, which refer to a collection of objects of similar type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
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[][] array4 = new int[2][];
A

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 initial-ize 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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which of the following statements are correct?
a The following code executes without an error or exception:
ArrayList lst = new ArrayList<>();
lst.add(10);
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.

A

Answer: d, e
Explanation: Option (a) is incorrect. The default type of a non-floating numeric lit-eral value is int. You can’t add an int to an ArrayList of type Long. You can pass val-ues 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 refer-ence 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 indi-vidual ArrayList elements aren’t cloned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which of the following statements are correct?
a An ArrayList offers a resizable array, which is easily managed using the meth-ods 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.

A

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 val-ues compared using the methods provided by the Collection framework classes.
Option (d) is incorrect. An array requires you to specify the total number of ele-ments 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
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 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.
j Line 11 throws an exception.
k Line 11 prints null.
A

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 oth-erwise. 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; oth-erwise, 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 run-time 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
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
A

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 vari-able 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
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
A

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 sub-string 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
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
d gZ
e game
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
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 Runtime exception
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
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
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the output of the following code?
String printDate = LocalDate.parse(“2057-08-11”)
.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(printDate);
a August 11, 2057T00:00
b Saturday Aug 11,2057T00:00
c 08-11-2057T00:00:00
d Compilation error
e Runtime exception

A

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 excep-tion 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly