Reviewed by Editorial Team
The ProProfs editorial team is comprised of experienced subject matter experts. They've collectively created over 10,000 quizzes and lessons, serving over 100 million users. Our team includes in-house content moderators and subject matter experts, as well as a global network of rigorously trained contributors. All adhere to our comprehensive editorial guidelines, ensuring the delivery of high-quality content.
Learn about Our Editorial Process
| By RubiyaSameen
R
RubiyaSameen
Community Contributor
Quizzes Created: 2 | Total Attempts: 2,863
| Attempts: 651 | Questions: 40
Please wait...
Question 1 / 40
0 %
0/100
Score 0/100
1. 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.

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.

Submit
Please wait...
About This Quiz
Core Java Test 4 - Quiz

CORE JAVA TEST 4 assesses knowledge in Java programming, focusing on class instance comparison, BitSet collections, Java Map interface, ArrayList features, Enumeration interface, and SortedSet usage. Key for learners enhancing Java skills.

Personalize your quiz and earn a certificate with your name on it!
2. The Enumeration interface allows a program to iterate its way through the elements of a container such as a Vector

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.

Submit
3. 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). 

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.

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

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.

Submit
5. 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)

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.

Submit
6. Which most closely matches a java description of a java map

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.

Submit
7. 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?

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.

Submit
8. 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]?

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

Submit
9. How does the set collection deal with duplicate elements?

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.

Submit
10. Which of the following most closely describes a bitset collection?

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.

Submit
11. Class Stack in package java.util extends class LinkedList

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.

Submit
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???  

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.

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

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.

Submit
14. 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?

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

Submit
15. 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?

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

Submit
16. 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)  

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

Submit
17. 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?

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

Submit
18. 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?

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.

Submit
19. 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?

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

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

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.

Submit
21. 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??

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.

Submit
22. 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?

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.

Submit
23. 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. 

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.

Submit
24. 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());
    }
}

Explanation

The method doubleValue() is undefined for the type X

Submit
25. 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?

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

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

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.

Submit
27. 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());
    }
}

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.

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

Explanation

not-available-via-ai

Submit
29. 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());
    }
}

Explanation

The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.

Submit
30. 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)

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.

Submit
31. 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?

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.

Submit
32. 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());
    }
}

Explanation

ClassCastException: Integer cannot be cast to Double.

Submit
33. 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 ???

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

Submit
34. 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 + " ");
        }
    }
}

Explanation

The construction for(;) can only iterate over an array or an instance of java.lang.Iterable.

Submit
35. 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?  

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.

Submit
36. 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.)

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.

Submit
37. 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)

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.

Submit
38. 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
        }
}

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.

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

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.

Submit
40. 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)

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.

Submit
View My Results

Quiz Review Timeline (Updated): Sep 7, 2023 +

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
Cancel
  • All
    All (40)
  • Unanswered
    Unanswered ()
  • Answered
    Answered ()
The hashCode method is used by the java.util.HashSet collection class...
The Enumeration interface allows a program to iterate its...
Properties method getProperty locates the value...
The hashCode method for a given class can be used to test for object...
Which collection class(es)allows you to grow or shrink its size and...
Which most closely matches a java description of a java map
Given:...
Import java.util.*;...
How does the set collection deal with duplicate elements?
Which of the following most closely describes a bitset collection?
Class Stack in package java.util extends...
Import java.util.*;...
Given:...
Public static Collection get()...
Import java.util.*;...
Given:...
Consider the following code snippets:...
A programmer has an algorithm that requires a java.util.List that...
Consider the following code snippet:...
Which of the following is the best-performing implementation of Set...
Given...
Consider the following code snippet:...
If you do not specify a capacity increment, the system will...
Given the code. What is the result?...
Consider the following code snippet:...
The hashCode method is used by the java.util.SortedSet collection...
Import java.util.*;...
Given a properly String array containing five elements,which range of...
Given the code. What is the result?...
Which of the following options give the names of data structures that...
Given:...
Given the code. What is the result?...
Given:...
Given the code. What is the result?...
Import java.util.*;...
Given:...
Given:...
Given the code. Select correct calls of methods. (Select all that...
Which of the following options are true about abstract implementations...
Which statements are true about comparing two instances of the same...
Alert!

Advertisement