Java OCA OCP Practice Question 2305

Question

Which declaration can be inserted at (1) so that the program compiles without errors?.

public class Main {
  // (1) INSERT DECLARATION HERE...
  public long getNum(String name) {
    Long number = accounts.get(name);
    return number == null ? 0 : number;
  }//from ww w. ja  v  a  2s  .  c  o m
  public void setNum(String name, long number) {
    accounts.put(name, number);
  }
}

Select the one correct answer.

  • (a) private Map<String, long> accounts = new HashMap<String, long>();
  • (b) private Map<String, Long> accounts = new HashMap<String, Long>();
  • (c) private Map<String<Long>> accounts = new HashMap<String<Long>>();
  • (d) private Map<String, Long> accounts = new Map<String, Long>();
  • (e) private Map accounts = new HashMap();


(b)

Note

  • (a) Primitive types are not permitted as type parameters.
  • (c) String is not a generic class.
  • (d) The interface Map cannot be instantiated.
  • (e) The method call accounts.getNum(name) returns an Object, which cannot be converted to a Long.



PreviousNext

Related