Java Fundamentals  «Prev  Next»
Lesson 1

Java Programming Language Fundamentals

Elements of the Java Programming Language

This module examines the fundamentals of the Java programming language. Topics covered in this module include tokens and comments, as well as data types, arrays, and strings. You will learn how Java evaluates expressions, and You will also learn about some of the different Java operators.

Module Learning Objectives

After completing the module, You will have the skills and knowledge necessary to:
  1. Describe how Java code is broken down into tokens
  2. Explain the different types of comments supported in Java
  3. Use Java's different data types
  4. Evaluate expressions in Java
  5. Use numeric, Boolean, string and assignment operators

[04 - Generics and Collections]

Question: Which of the following code fragments is/are appropriate usage(s) of generics? [Select 1 option: ]
  1. Map < String, List <String> > myMap = new HashMap();
  2. List <String> list = new ArrayList< >(); 
    list.addAll(new ArrayList< >()); 
  3. List <String> list = new ArrayList< >();
    List<? extends String> list2 = new ArrayList< >();
  4. List< >(); list = new ArrayList <String >();

Answer: c
  1. Although this is valid code, it is not a good use of generics because when you execute new HashMap(), you create a raw HashMap and it will produce a warning at compile time.
    Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond operator. that is, you must use new HashMap<>() in this case.
  2. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. In this option, the last line will not compile because the list.addAll() method expects
    Collection<? extends String> 

    and so the compiler cannot infer the generic type for ArrayList.
  3. c. is the correct answer.
  4. The diamond operator is used at the place of creation of the object and not at the place of variable type declaration.
    So it should be: List<String> list = new ArrayList< >();