Core Java Test 4

Approved & Edited by ProProfs Editorial Team
The editorial team at ProProfs Quizzes consists of a select group of subject experts, trivia writers, and quiz masters who have authored over 10,000 quizzes taken by more than 100 million users. This team includes our in-house seasoned quiz moderators and subject matter experts. Our editorial experts, spread across the world, are rigorously trained using our comprehensive guidelines to ensure that you receive the highest quality quizzes.
Learn about Our Editorial Process
| By RubiyaSameen
R
RubiyaSameen
Community Contributor
Quizzes Created: 2 | Total Attempts: 2,123
Questions: 40 | Attempts: 637

SettingsSettingsSettings
Core Java Test 4 - Quiz

COLLECTION
UTILITY PACKAGE


Questions and Answers
  • 1. 

    Which statements are true about comparing two instances of the same class,given that the equals() and hashCode() methods have been properly overridden? (choose all that apply)

    • A.

      If the equals()methood returns true,the hashCode() comparison==might return false.

    • B.

      If the equals()methood returns false,the hashCode() comparison==might return true.

    • C.

      If the hashCode() comparison==returns true,the equals() method must return true

    • D.

      If the hashCode() comparison==returns true,the equals() method might return true

    • E.

      If the hashCode() comparison!=returns true,the equals() method must return true

    Correct Answer(s)
    B. If the equals()methood returns false,the hashCode() comparison==might return true.
    D. If the hashCode() comparison==returns true,the equals() method might return true
    E. If the hashCode() comparison!=returns true,the equals() method must return true
    Explanation
    If the equals() method returns false, it means that the two instances are not equal. In this case, the hashCode() comparison might still return true because the hashCode() method can generate the same hash code for different objects. This is known as a hash code collision.

    If the hashCode() comparison returns true, it means that the hash codes of the two instances are the same. However, this does not guarantee that the instances are equal. The equals() method might still return true, but it is also possible for it to return false.

    If the hashCode() comparison returns false, it means that the hash codes of the two instances are different. In this case, the equals() method must return true because different hash codes imply different objects.

    Rate this question:

  • 2. 

    Which of the following most closely describes a bitset collection?

    • A.

      A class that contains groups of unique sequences of bits. 

    • B.

      A method for flipping individual bits in instance of a primitive type.

    • C.

      An array of boolean primitives that indicate zeros or ones.

    • D.

      A collection for storing bits as on-off information, like a vector of bits.

    Correct Answer
    D. A collection for storing bits as on-off information, like a vector of bits.
    Explanation
    A bitset collection is a data structure that is used to store and manipulate bits. It is similar to a vector of bits, where each bit can be either on or off. This collection is commonly used in scenarios where memory efficiency and manipulation of individual bits are important, such as in algorithms that involve bitwise operations or in situations where a large number of boolean values need to be stored compactly.

    Rate this question:

  • 3. 

    Which most closely matches a java description of a java map

    • A.

      A vector of arrays for a 2D geographic representation.

    • B.

      A class for containing unique array elements.

    • C.

      A class for containing unique vector elements.

    • D.

      An interface that ensures that implementing classes cannot contain duplicate keys.

    Correct Answer
    D. An interface that ensures that implementing classes cannot contain duplicate keys.
    Explanation
    The correct answer is an interface that ensures that implementing classes cannot contain duplicate keys. This is because a Java map is a data structure that stores key-value pairs, and it does not allow duplicate keys. The interface mentioned in the answer ensures that any class implementing it will adhere to this rule of not allowing duplicate keys in the map.

    Rate this question:

  • 4. 

    Which collection class(es)allows you to grow or shrink its size and provides indexed access to its elements,but whose methods are not synchronised??(choose all that aaply)

    • A.

      Java.util.HashSet

    • B.

      Java.util.LinkedHashSet

    • C.

      Java.util.List

    • D.

      Java.util.ArrayList

    • E.

      Java.util.Vector

    • F.

      Java.util.PriorityQueue

    Correct Answer
    D. Java.util.ArrayList
    Explanation
    The java.util.ArrayList class allows you to grow or shrink its size and provides indexed access to its elements. Its methods are not synchronized, meaning that they are not thread-safe. This allows for better performance in single-threaded environments but may lead to data corruption if accessed concurrently by multiple threads.

    Rate this question:

  • 5. 

    The Enumeration interface allows a program to iterate its way through the elements of a container such as a Vector

    • A.

      True

    • B.

      False

    Correct Answer
    A. True
    Explanation
    The Enumeration interface is used to iterate through the elements of a container, such as a Vector. It provides methods to check if there are more elements in the container and to retrieve the next element. Therefore, the statement that the Enumeration interface allows a program to iterate through the elements of a container like a Vector is true.

    Rate this question:

  • 6. 

    The hashCode method is used by the java.util.SortedSet collection class to order the elements within that set.

    • A.

      True

    • B.

      False

    Correct Answer
    B. False
    Explanation
    The explanation for the given answer is that the hashCode method is not used by the java.util.SortedSet collection class to order the elements within the set. The SortedSet interface in Java uses the compareTo method, not the hashCode method, to order its elements. The hashCode method is used for generating hash codes for objects in order to efficiently store and retrieve them from hash-based data structures like HashMap or HashSet.

    Rate this question:

  • 7. 

    The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.

    • A.

      True

    • B.

      False

    Correct Answer
    A. True
    Explanation
    The explanation for the given correct answer is that the hashCode method in Java is indeed used by the HashSet collection class to group elements into hash buckets. This allows for efficient retrieval of elements from the set based on their hash values.

    Rate this question:

  • 8. 

    The hashCode method for a given class can be used to test for object inequality, but NOT object equality, for that class.

    • A.

      True

    • B.

      False

    Correct Answer
    A. True
    Explanation
    The hashCode method in a class is used to generate a unique identifier for each object of that class. This identifier can be used to check if two objects are not equal, but it cannot be used to determine if two objects are equal. The reason for this is that multiple objects can have the same hash code, but they may still be different objects. Therefore, the hashCode method can only be used to test for object inequality, not object equality.

    Rate this question:

  • 9. 

    Public static Collection get()  { Collection sorted = new LinkedList();  sorted.add("B"); sorted.add("C"); sorted.add("A");  return sorted; } public static void main(String[] args)  {  for (Object obj: get())  {  System.out.print(obj + ", ");  } }   What is the result?

    • A.

      A,B,C

    • B.

      B,C,A

    • C.

      Compilation fails

    • D.

      The code runs with no output

    • E.

      Exception is thrown at runtime

    Correct Answer
    B. B,C,A
    Explanation
    The code will print "B, C, A" as the output. The get() method returns a LinkedList collection with elements "B", "C", and "A" in that order. The for-each loop in the main method iterates over each element in the collection and prints it followed by a comma. Therefore, the output will be "B, C, A".

    Rate this question:

  • 10. 

    Properties method getProperty locates the value associated with the specified key. If the key is not found in this Properties object,getProperty attempts to locate the key in the default Properties object (if there is one). 

    • A.

      True

    • B.

      False

    Correct Answer
    A. True
    Explanation
    The explanation for the given correct answer is that the Properties method getProperty is used to find the value associated with a specific key. If the key is not found in the current Properties object, the method will attempt to locate the key in the default Properties object, if one exists. Therefore, the statement is true.

    Rate this question:

  • 11. 

    Import java.util.*; public class TryMe {     public static void main(String args[]) {         Queue<String> q = new PriorityQueue<String>();         q.add("3");         q.add("1");         q.add("2");         System.out.print(q.poll() + " ");         System.out.print(q.peek() + " ");         System.out.print(q.peek());     } }

    • A.

      1 2 3

    • B.

      3 2 1

    • C.

      1 2 2

    • D.

      3 1 1

    • E.

      2 3 3

    • F.

      1 1 2

    Correct Answer
    C. 1 2 2
    Explanation
    peek() - retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
    poll() - retrieves and removes the head of this queue, or returns null if this queue is empty.

    Rate this question:

  • 12. 

    Import java.util.*; public class TestArrayList { public static void main(String args[]) { List test =new ArrayList(); String s="hi"; testadd(s); testadd(s+s); System.out.println(test.size()); System.out.println(test.contains(42)); System.out.println(test.contains("hihi")); test.remove("hi"); System.out.println(test.size()); } }   What is the output of this program???  

    • A.

      3 false true 2

    • B.

      2 false true 3

    • C.

      3 true false 2

    • D.

      2 true false 3

    Correct Answer
    A. 3 false true 2
    Explanation
    The output of this program is "3 false true 2". This is because the program first adds the string "hi" to the ArrayList, then adds the concatenation of "hi" with itself ("hihi") to the ArrayList. The size of the ArrayList is then printed, which is 2. The program then checks if the ArrayList contains the integer 42, which it does not, so it prints false. Next, it checks if the ArrayList contains the string "hihi", which it does, so it prints true. Finally, the program removes the string "hi" from the ArrayList, resulting in a size of 1, which is printed as 2.

    Rate this question:

  • 13. 

    Import java.util.*; public class WrappedString  {  private String s; public WrappedString(String s)  {  this.s = s;  }  public static void main(String[] args)  {  HashSeths = new HashSet(); WrappedString ws1 = new WrappedString("aardvark");  WrappedString ws2 = new WrappedString("aardvark");  String s1 = new String("aardvark"); String s2 = new String("aardvark");  hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2); System.out.println(hs.size());  }  }   What is the result?  

    • A.

      0

    • B.

      1

    • C.

      2

    • D.

      3

    • E.

      4

    • F.

      Compilation error

    • G.

      Exception is thrown at runtime

    Correct Answer
    D. 3
    Explanation
    The result of the code is 3. This is because the HashSet only allows unique elements, and in this case, the HashSet will consider the two WrappedString objects (ws1 and ws2) as separate elements, even though they have the same value. Additionally, the two String objects (s1 and s2) will also be considered as separate elements. Therefore, the HashSet will have a total of 3 unique elements.

    Rate this question:

  • 14. 

    Import java.util.*; public class PQ { public static void main(String[] args)  {  PriorityQueue pq = new PriorityQueue(); pq.add("carrot"); pq.add("apple"); pq.add("banana");  System.out.println(pq.poll() + ":" + pq.peek()); }  }   What is the result?

    • A.

      Apple:apple

    • B.

      Carrot:apple

    • C.

      Apple:banana

    • D.

      Banana:apple

    • E.

      Carrot:carrot

    • F.

      Carrot:banana

    Correct Answer
    C. Apple:banana
    Explanation
    The code creates a PriorityQueue and adds three strings: "carrot", "apple", and "banana". The poll() method removes and returns the first element in the PriorityQueue, which is "apple". The peek() method returns the first element in the PriorityQueue without removing it, which is "banana". Therefore, the result is "apple:banana".

    Rate this question:

  • 15. 

    Import java.util.*; public class Example  { public static void main(String[] args) { // insert code here set.add(new Integer(2));  set.add(new Integer(1)); System.out.println(set);  }  }   Which code, inserted at line 4, guarantees that this program will output [1, 2]?

    • A.

      Set set = new TreeSet();

    • B.

      Set set = new HashSet();

    • C.

      Set set = new SortedSet();

    • D.

      Set set = new LinkedHashSet();

    • E.

      Set set = new SortedList();

    Correct Answer
    A. Set set = new TreeSet();
    Explanation
    The code "Set set = new TreeSet();" guarantees that this program will output [1, 2]. This is because TreeSet is an implementation of the Set interface that stores elements in sorted order. When elements are added to a TreeSet, they are automatically sorted based on their natural ordering or a custom comparator. In this case, the elements 2 and 1 are added to the TreeSet, and they will be sorted in ascending order, resulting in the output [1, 2].

    Rate this question:

  • 16. 

    If you do not specify a capacity increment, the system will automatically add 2 to the size of the Vector each time additional capacity is needed. 

    • A.

      True

    • B.

      False

    Correct Answer
    B. False
    Explanation
    If you do not specify a capacity increment, the system will not automatically add 2 to the size of the Vector each time additional capacity is needed. The default behavior of the Vector class is to double the size of the underlying array when additional capacity is required.

    Rate this question:

  • 17. 

    How does the set collection deal with duplicate elements?

    • A.

      An exception is thrown if you attempt to add an element with a duplicate value.

    • B.

      The add method returns false if you attempt to add an element with a duplicate value.

    • C.

      A set may contain elements that return duplicate values from a call to the equals method.

    • D.

      Duplicate values will cause an error at compile time.

    Correct Answer
    B. The add method returns false if you attempt to add an element with a duplicate value.
    Explanation
    The add method in the set collection returns false if you try to add an element with a duplicate value. This means that if you try to add an element that already exists in the set, it will not be added and the method will return false to indicate that the addition was unsuccessful. This behavior allows the set collection to effectively deal with duplicate elements by not allowing them to be added in the first place.

    Rate this question:

  • 18. 

    Given: TreeSet map=new TreeSet(); map.add("one"); map.add("two"); map.add("three"); map.add("four"); map.add("one"); Iterator it=map.iterator(); while(it.hasNext()) { System.out.println(it.next()+" "); }   what is the result ???

    • A.

      Compialtion fails

    • B.

      One two three four

    • C.

      Four one three two

    • D.

      One two three four one

    • E.

      One four three two one

    • F.

      An exception is thrown at runtime

    • G.

      The print order is not guaranteed

    Correct Answer
    D. One two three four one
    Explanation
    The code creates a TreeSet named "map" and adds the strings "one", "two", "three", "four", and "one" to it. Since TreeSet does not allow duplicate elements, the second "one" is not added to the set. The code then creates an iterator named "it" and iterates over the elements in the set. The iterator returns the elements in ascending order, so the result will be "four one three two".

    Rate this question:

  • 19. 

    Given: import java.util.* class AlgaeDiesel{ public static void main(String[] args) { String sa={"foo","bar","baz" }; //insert method invocations here } }   what java.util.Arrays and/or java.util.Collections methods could you use  to convert sa to a List and then search the List to find the index  of the element whose valueis "foo"??(choose three methods)

    • A.

      Sort()

    • B.

      AsList()

    • C.

      ToList

    • D.

      Search()

    • E.

      SortList()

    • F.

      Contains()

    • G.

      BinarySearch()

    Correct Answer(s)
    A. Sort()
    B. AsList()
    G. BinarySearch()
    Explanation
    The correct answer is sort(), asList(), binarySearch(). The sort() method is used to sort the elements in the array in ascending order. The asList() method is used to convert the array to a List. The binarySearch() method is then used to search for the index of the element "foo" in the List.

    Rate this question:

  • 20. 

    Given:  public static void search(List list)  {  list.clear();    list.add("b");    list.add("a");    list.add("c");    System.out.println(Collections.binarySearch(list, "a"));  }   What is the result of calling search with a valid List implementation?

    • A.

      0

    • B.

      1

    • C.

      2

    • D.

      A

    • E.

      B

    • F.

      C

    • G.

      Result is undefined

    Correct Answer
    G. Result is undefined
    Explanation
    The result is undefined because the list is cleared before adding elements to it. The binarySearch method requires the list to be sorted in ascending order for accurate results. However, since the list is cleared before adding elements, it is not sorted and the behavior of the binarySearch method is unpredictable.

    Rate this question:

  • 21. 

    Given: ArrayList a = new ArrayList(); containing the values {“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”} Which code will return 2?

    • A.

      Collections. sort(a, a.reverse()); int result = Collections.binarySearch(a, “6”);

    • B.

      Comparator c = Collections.reverseOrder(); Collections.sort(a, c); int result = Collections.binarySearch(a, “6”);

    • C.

      Comparator c = Collections.reverseOrder(a); Collections.sort(a, c); int result = Collections.binarySearch(a, “6”,c);

    • D.

      Comparator c = new InverseComparator(new Comparator()); Collections.sort(a); int result = Collections.binarySearch(a, “6”,c);

    Correct Answer
    B. Comparator c = Collections.reverseOrder(); Collections.sort(a, c); int result = Collections.binarySearch(a, “6”);
    Explanation
    The correct answer is the second option. By using the reverseOrder() method from the Collections class, the ArrayList is sorted in reverse order. Then, the binarySearch() method is used to find the index of the element "6" in the sorted ArrayList. Since "6" is the second element in the reversed sorted ArrayList, the result will be 2.

    Rate this question:

  • 22. 

    Given:  public class Key { private long id1; private long id2;    // class Key methods    }   A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap.Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)

    • A.

      Public int hashCode()

    • B.

      Public boolean equals(Key k)

    • C.

      Public int compareTo(Object o)

    • D.

      Public boolean equals(Object o)

    • E.

      Public boolean compareTo(Key k)

    Correct Answer(s)
    A. Public int hashCode()
    D. Public boolean equals(Object o)
    Explanation
    To assure that Key works correctly as a key in a java.util.HashMap, the programmer should override the hashCode() method and the equals(Object o) method. The hashCode() method is used to generate a unique hash code for each Key object, which is used by the HashMap to determine the bucket in which to store the key-value pair. The equals(Object o) method is used to compare two Key objects for equality, allowing the HashMap to correctly retrieve the value associated with a given key.

    Rate this question:

  • 23. 

    Given:  import java.util.*;   public class LetterASort {  public static void main(String[] args)  {  ArrayList strings = new ArrayList();    strings.add("aAaA");   strings.add("AaA");   strings.add("aAa");    strings.add("AAaa");    Collections.sort(strings);    for (String s : strings) { System.out.print(s + " ");  }  }  }   What is the result?

    • A.

      Compilation fails.

    • B.

      AAaA aAa AAaa AaA

    • C.

      AAaa AaA aAa aAaA

    • D.

      AaA AAaa aAaA aAa

    • E.

      aAa AaA aAaA AAaa

    • F.

      An exception is thrown at runtime.

    Correct Answer
    C. AAaa AaA aAa aAaA
    Explanation
    The code creates an ArrayList called "strings" and adds four strings to it. The strings are then sorted using the Collections.sort() method, which sorts the strings in lexicographic order. The sorted strings are then printed using a for-each loop. The output will be "AAaa AaA aAa aAaA" because the strings are sorted in lexicographic order, with uppercase letters appearing before lowercase letters.

    Rate this question:

  • 24. 

    Given: import java.util.*; class Flubber { public static void main(String[] args) { List x=new ArrayList(); x.add("x"); x.add("xx"); x.add("Xx"); //insert code here for(String s:x) System.out.println(s); }} the output is: xx Xx  x which code, inserted will produce the preceding output?? (choose al that apply)  

    • A.

      Collections.sort(x);

    • B.

      Comparable c=Collections.reverse(); Collections.sort(x,c);

    • C.

      Collections.sort(x,c);

    • D.

      Comparable c=Collections.reverseOrder(); Collections.sort(x,c);

    • E.

      Comparator c=Collections.reverseOrder(); Collections.sort(x,c);

    Correct Answer
    E. Comparator c=Collections.reverseOrder(); Collections.sort(x,c);
    Explanation
    The correct answer is "Comparator c=Collections.reverseOrder(); Collections.sort(x,c);". This code will sort the list "x" in reverse order using the Comparator interface and the reverseOrder() method from the Collections class. This will result in the output being printed in the order "xx", "Xx", and "x".

    Rate this question:

  • 25. 

    Given the code. What is the result? public class TrickyNum<X extends Number> {         private X x;        public TrickyNum(X x) {         this.x = x;     }     private double getDouble() {         return x.doubleValue();     }     public static void main(String args[]) {         TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1));         System.out.print(a.getDouble());     } }

    • A.

      Compilation fails.

    • B.

      An exception is thrown at runtime.

    • C.

      "1.0" is printed.

    • D.

      "1" is printed.

    Correct Answer
    C. "1.0" is printed.
    Explanation
    The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.

    Rate this question:

  • 26. 

    Given the code. What is the result? public class TrickyNum<X extends Object> {      private X x;      public TrickyNum(X x) {         this.x = x;     }       private double getDouble() {         return ((Double) x).doubleValue();     }        public static void main(String args[]) {         TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1));         System.out.print(a.getDouble());     } }

    • A.

      Compilation fails.

    • B.

      An exception is thrown at runtime.

    • C.

      "1.0" is printed.

    • D.

      "1" is printed.

    Correct Answer
    B. An exception is thrown at runtime.
    Explanation
    ClassCastException: Integer cannot be cast to Double.

    Rate this question:

  • 27. 

    Given the code. What is the result? public class TrickyNum<X extends Object> {       private X x;       public TrickyNum(X x) {         this.x = x;     }        private double getDouble() {         return x.doubleValue();     }         public static void main(String args[]) {         TrickyNum<Integer> a = new TrickyNum<Integer>(new Integer(1));         System.out.print(a.getDouble());     } }

    • A.

      Compilation fails.

    • B.

      An exception is thrown at runtime.

    • C.

      "1.0" is printed.

    • D.

      "1" is printed.

    Correct Answer
    A. Compilation fails.
    Explanation
    The method doubleValue() is undefined for the type X

    Rate this question:

  • 28. 

    Given the code. What is the result? import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class TryMe {     public static void main(String args[]) {         List list = new LinkedList<String>();         list.add("one");         list.add("two");         list.add("three");                  Collections.reverse(list);         Iterator iter = list.iterator();                  for (Object o : iter) {             System.out.print(o + " ");         }     } }

    • A.

      "three two one " is printed

    • B.

      "one two three " is printed

    • C.

      Nothing is printed

    • D.

      Compilation fails

    • E.

      An exception is thrown at runtime

    Correct Answer
    D. Compilation fails
    Explanation
    The construction for(;) can only iterate over an array or an instance of java.lang.Iterable.

    Rate this question:

  • 29. 

    Given the code. Select correct calls of methods. (Select all that apply) import java.util.*; class Empty {    } class Extended extends Empty {   } public class TryMe {             public static void doStuff1(List<Empty> list) {                 // some code         }         public static void doStuff2(List list) {                         // some code         }         public static void doStuff3(List extends Empty> list) {                 // some code                     }              public static void main(String args[]) {                 List<Empty> list1 = new LinkedList<Empty>();                 List<Extended> list2 = new LinkedList<Extended>();                                // more code here         } }

    • A.

      DoStuff1(list1);

    • B.

      DoStuff2(list2);

    • C.

      DoStuff2(list1);

    • D.

      DoStuff3(list1);

    • E.

      DoStuff3(list2);

    • F.

      DoStuff1(list2);

    Correct Answer(s)
    A. DoStuff1(list1);
    B. DoStuff2(list2);
    C. DoStuff2(list1);
    D. DoStuff3(list1);
    E. DoStuff3(list2);
    Explanation
    The correct calls of methods are doStuff1(list1), doStuff2(list2), doStuff2(list1), doStuff3(list1), and doStuff3(list2).


    - doStuff1(list1) is a correct call because it matches the parameter type of List.
    - doStuff2(list2) is a correct call because it accepts a raw List, and list2 is a List which is a subtype of List.
    - doStuff2(list1) is a correct call because it also accepts a raw List, and list1 is a List.
    - doStuff3(list1) is a correct call because it accepts a List that extends Empty, and list1 is a List.
    - doStuff3(list2) is a correct call because it also accepts a List that extends Empty, and list2 is a List which is a subtype of List.

    Rate this question:

  • 30. 

    Given a properly String array containing five elements,which range of results could a proper invocation of Arrays.binarySearch() produce???

    • A.

      0 through 4

    • B.

      0 through 5

    • C.

      -1 through 4

    • D.

      -1 through 5

    • E.

      -5 through 4

    • F.

      -5 through 5

    • G.

      -6 through 4

    • H.

      -6 through 5

    Correct Answer
    G. -6 through 4
  • 31. 

    Given public static void before() { Set set=new TreeSet(); set.add("2"); set.add(3); set.add("1"); Iterator it=set.iterator(); while(it.hasNext()) Sytem.out.println(it.next()+" "); } which of the following statements are true??

    • A.

      Before () method will print 1 2

    • B.

      Before () method will print 1 2 3

    • C.

      Before () method wil print three numbers,but order cannot be determined.

    • D.

      Before () method will not compile

    • E.

      Before () method will throw an exception at runtime

    Correct Answer
    E. Before () method will throw an exception at runtime
    Explanation
    The before() method will throw an exception at runtime because the line "Sytem.out.println(it.next()+" ");" has a typo. It should be "System.out.println(it.next()+" ");" with a capital 'S' in System.

    Rate this question:

  • 32. 

    Consider the following code snippets: class GC2 { public GC2 getIt(GC2 gc2) { return gc2; } public static void main(String a[]) { GC2 g = GC2(); GC2 c = GC2(); c = g.getIt(c); } } How many objects are eligible for Garbage Collection?

    • A.

      Two

    • B.

      None of the objects are eligible

    • C.

      Three

    • D.

      Four

    • E.

      One

    Correct Answer
    B. None of the objects are eligible
    Explanation
    The code snippet creates two objects of type GC2, named "g" and "c". The "getIt" method is called on object "g" passing object "c" as an argument. However, since the "getIt" method simply returns the object passed as an argument, there are no objects that become eligible for garbage collection in this code. Therefore, the correct answer is "none of the objects are eligible".

    Rate this question:

  • 33. 

    Consider the following code snippet:   import java.util.*; public class TestCol8 { public static void main(String argv[]) { TestCol8 junk = new TestCol8(); junk.sampleMap();   } public void sampleMap() { TreeMap tm = new TreeMap(); tm.put("a","Hello");   tm.put("b","Java");   tm.put("c","World"); Iterator it = tm.keySet().iterator(); while(it.hasNext()){ System.out.print(it.next()); } } } What will be the output of the above code snippet?

    • A.

      Abc

    • B.

      Runtime error

    • C.

      Compile error

    • D.

      HelloJavaWorld

    • E.

      HWJ

    Correct Answer
    A. Abc
    Explanation
    The code snippet creates a TreeMap object and adds three key-value pairs to it. Then, it retrieves the set of keys from the TreeMap and iterates over them using an iterator. The iterator's next() method is called in each iteration and the key is printed. Therefore, the output will be "abc".

    Rate this question:

  • 34. 

    Consider the following code snippet:   import java.util.*; public class TestCol3 { public static void main(String[] args) { List l = new ArrayList(); l.add("One"); l.add("Two"); l.add("Three"); l.add("Four"); l.add("One"); l.add("Four"); Set h = new HashSet(); h.addAll(l); System.out.println("Size:" + l.size() + h.size()); } } What will be the output of the following code snippet?

    • A.

      Size: 64

    • B.

      Size: 44

    • C.

      Size: 66

    • D.

      Size: 46

    • E.

      Compilation error

    Correct Answer
    A. Size: 64
    Explanation
    The output of the code snippet will be "Size: 64". This is because the code first creates an ArrayList named "l" and adds six elements to it. Then, it creates a HashSet named "h" and adds all the elements from "l" to it. Since a HashSet does not allow duplicate elements, the duplicate elements "One" and "Four" will be removed. Finally, the code prints the size of "l" (6) and the size of "h" (4), resulting in the output "Size: 64".

    Rate this question:

  • 35. 

    Class Stack in package java.util extends class LinkedList

    • A.

      True

    • B.

      False

    Correct Answer
    B. False
    Explanation
    The given statement is false. The class Stack in package java.util does not extend the class LinkedList. In fact, the class Stack in java.util package is a subclass of the class Vector, not LinkedList. Therefore, the correct answer is False.

    Rate this question:

  • 36. 

    A programmer has an algorithm that requires a java.util.List that provides an efficient implementation of add(0, object), but does NOT need to support quick random access. What supports these requirements?

    • A.

      Java.util.Queue

    • B.

      Java.util.ArrayList

    • C.

      Java.util.LinearList

    • D.

      Java.util.LinkedList

    Correct Answer
    D. Java.util.LinkedList
    Explanation
    The java.util.LinkedList class supports the requirements mentioned in the question. It provides an efficient implementation of the add(0, object) method, which allows adding an element at the beginning of the list. It does not need to support quick random access, which means accessing elements by index may not be as efficient as in other list implementations like java.util.ArrayList. Therefore, java.util.LinkedList is the correct choice for the given requirements.

    Rate this question:

  • 37. 

    Which of the following options give the names of data structures that can be used for elements that have ordering, but no duplicates? (Choose 2)

    • A.

      SortedSet

    • B.

      TreeSet

    • C.

      ArrayList

    • D.

      List

    • E.

      Set

    Correct Answer(s)
    A. SortedSet
    B. TreeSet
    Explanation
    SortedSet and TreeSet are both data structures that can be used for elements that have ordering but no duplicates. SortedSet is an interface in Java that extends the Set interface and maintains the elements in ascending order. TreeSet is a class in Java that implements the SortedSet interface and stores elements in a sorted order using a binary search tree. Both data structures ensure that there are no duplicate elements in the collection while maintaining the order of the elements.

    Rate this question:

  • 38. 

    Which of the following is the best-performing implementation of Set interface?

    • A.

      HashSet

    • B.

      TreeSet

    • C.

      HashTable

    • D.

      LinkedHashSet

    • E.

      SortedSet

    Correct Answer
    A. HashSet
    Explanation
    HashSet is the best-performing implementation of the Set interface because it offers constant-time performance for basic operations like add, remove, and contains. It achieves this by using a hash table to store elements, which allows for efficient retrieval and insertion. TreeSet, on the other hand, is a sorted implementation of Set that offers logarithmic time complexity for these operations. HashTable is an older implementation that is now considered legacy, and LinkedHashSet maintains a linked list to preserve insertion order, which adds some overhead. SortedSet is not an implementation but rather an interface that is implemented by TreeSet.

    Rate this question:

  • 39. 

    Consider the following code snippet: import java.util.*; public class TestCol4 { public static void main(String[] args) { Set h = new HashSet(); h.add("One"); h.add("Two"); h.add("Three"); h.add("Four"); h.add("One"); h.add("Four"); List l = new ArrayList(); l.add("One"); l.add("Two"); l.add("Three"); h.retainAll(l); System.out.println("Size:" + l.size() + h.size()); } } What will be the output of the above code snippet?

    • A.

      Size:33

    • B.

      Size:36

    • C.

      Size:66

    • D.

      Compilation error

    • E.

      Size:66

    Correct Answer
    A. Size:33
    Explanation
    The output of the code snippet will be "size:33". This is because the HashSet "h" retains only the elements that are present in the ArrayList "l". Since both "One", "Two", and "Three" are common elements in both sets, they are retained in "h". Therefore, the size of "h" will be 3, and the size of "l" will also be 3.

    Rate this question:

  • 40. 

    Which of the following options are true about abstract implementations in Collections?(choose 3)

    • A.

      It provides static factory class

    • B.

      All major implementations like Hashtable, Vectors are supported

    • C.

      They provide hooks for custom implementations

    • D.

      All major interfaces are supported

    • E.

      Map is not supported

    Correct Answer(s)
    A. It provides static factory class
    C. They provide hooks for custom implementations
    D. All major interfaces are supported
    Explanation
    Abstract implementations in Collections provide a static factory class, which allows for the creation of instances of the abstract implementation. They also provide hooks for custom implementations, allowing developers to override certain methods and customize the behavior of the implementation. Additionally, all major interfaces are supported by abstract implementations, meaning that they can be used interchangeably with other implementations that adhere to the same interface.

    Rate this question:

Quiz Review Timeline +

Our quizzes are rigorously reviewed, monitored and continuously updated by our expert board to maintain accuracy, relevance, and timeliness.

  • Current Version
  • Sep 07, 2023
    Quiz Edited by
    ProProfs Editorial Team
  • Dec 18, 2011
    Quiz Created by
    RubiyaSameen
Back to Top Back to top
Advertisement
×

Wait!
Here's an interesting quiz for you.

We have other quizzes matching your interest.