Java OCA OCP Practice Question 3171

Question

Which code, when inserted independently at (1), will result in the following output from the program: {be=2, not=1, or=1, to=2}?

import java.util.Map;
import java.util.TreeMap;
public class Main {
  public static void main(String[] args) {
    Map<String, Integer> freqMap = new TreeMap<String, Integer>();
    for (String key : new String[] {"to", "be", "or", "not", "to", "be"}) {
      // (1) INSERT CODE HERE ...
    }//w  ww .  ja va 2 s. com
    System.out.println(freqMap);
  }
}

Select the two correct answers.

(a) Integer frequency = freqMap.get(key);
    frequency = (frequency == 0) ? 1 : frequency+1;
    freqMap.put(key, frequency);//  w  ww . j  av  a  2 s .  c  o m

(b) Integer frequency = freqMap.get(key);
    frequency = (frequency == null) ? 1 : frequency+1;
    freqMap.put(key, frequency);
(c)  int frequency = freqMap.get(key);
     frequency = (frequency == 0) ? 1 : frequency+1;
     freqMap.put(key, frequency);

(d)  Integer frequency = (!freqMap.containsKey(key)) ? 1 : freqMap.get(key)+1;
     freqMap.put(key, frequency);


(b) and (d)

Note

Both (a) and (c) result in a NullPointerException: (a) in the expression (frequency == 0) and (b) in the first assignment.

In both cases, the reference frequency has the value null, which cannot be boxed or unboxed.




PreviousNext

Related