Java 7: Type inference

  Java Features     Java 5     Java 7     Java 8  
Java 7 features
 Binary literals |   Strings in switch statements |   Catching multiple exceptions |   Try with resources |   Type inference |   Underscores in numeric literals |   By date 

Type inference is included in JSE7. As long as the compiler can infer the arguments type from the context, you can use an empty set of parameters type <>. We call this pair of angle brackets the diamond. See the example below! For more info click here to read Oracle’s explanation.

Example 1: Type inference code

What is the output of the following code?

import java.util.ArrayList;
import java.util.List;

public class TypeInference
  public static void main(String[] args)
    // Diamond feature <>
    List<String> listCities = new ArrayList<>();
    listCities.add("New York City");
    for(String element: listCities)
      System.out.print(element + ", ");
Author: Sar Maroof

Answer explanation

The answer is the same whether you use the type interference or Java 6.

The correct answer is: London, New York City, Moscow,.

Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply