Java Programming - Objects and Collections

Exercise : Objects and Collections - General Questions
6.
Which interface provides the capability to store objects using a key-value pair?
Java.util.Map
Java.util.Set
Java.util.List
Java.util.Collection
Answer: Option
Explanation:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.


7.
Which collection class allows you to associate its elements with key values, and allows you to retrieve objects in FIFO (first-in, first-out) sequence?
java.util.ArrayList
java.util.LinkedHashMap
java.util.HashMap
java.util.TreeMap
Answer: Option
Explanation:

LinkedHashMap is the collection class used for caching purposes. FIFO is another way to indicate caching behavior. To retrieve LinkedHashMap elements in cached order, use the values() method and iterate over the resultant collection.


8.
Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization?
java.util.SortedMap
java.util.TreeMap
java.util.TreeSet
java.util.Hashtable
Answer: Option
Explanation:

Hashtable is the only class listed that provides synchronized methods. If you need synchronization great; otherwise, use HashMap, it's faster.


9.
Which is valid declaration of a float?
float f = 1F;
float f = 1.0;
float f = "1";
float f = 1.0d;
Answer: Option
Explanation:

Option A is valid declaration of float.

Option B is incorrect because any literal number with a decimal point u declare the computer will implicitly cast to double unless you include "F or f"

Option C is incorrect because it is a String.

Option D is incorrect because "d" tells the computer it is a double so therefore you are trying to put a double value into a float variable i.e there might be a loss of precision.


10.
/* Missing Statement ? */
public class foo 
{
    public static void main(String[]args)throws Exception 
    {
        java.io.PrintWriter out = new java.io.PrintWriter(); 
        new java.io.OutputStreamWriter(System.out,true); 
        out.println("Hello"); 
    } 
}
What line of code should replace the missing statement to make this program compile?
No statement required.
import java.io.*;
include java.io.*;
import java.io.PrintWriter;
Answer: Option
Explanation:

The usual method for using/importing the java packages/classes is by using an import statement at the top of your code. However it is possible to explicitly import the specific class that you want to use as you use it which is shown in the code above. The disadvantage of this however is that every time you create a new object you will have to use the class path in the case "java.io" then the class name in the long run leading to a lot more typing.