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("London"); listCities.add("New York City"); listCities.add("Moscow"); 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,.
Suggested Articles
![]() ![]() ![]() |