Type inference lets the Java compiler figure out generic types for you, so you don’t have to write them out every time. It makes code shorter and cleaner.
Example Without Type Inference
List<String> list = new ArrayList<String>();
Code language: JavaScript (javascript)
With type inference (Java 7+):
List<String> list = new ArrayList<>();
Code language: PHP (php)
The <>
is called the diamond operator, and the compiler understands the type from the left-hand side.
Type Inference in Methods
You don’t have to specify types when calling generic methods — the compiler infers them
public static <T> T pick(T a, T b) {
return a;
}
String result = pick("Java", "Generics"); // Inferred as <String>
Integer number = pick(1, 2); // Inferred as <Integer>
Code language: JavaScript (javascript)
Works with Lambdas and Streams (Java 8+)
List<String> names = List.of("LotusJavaPrince", "Mahesh");
names.forEach(name -> System.out.println(name)); // 'name' is inferred as String
Code language: PHP (php)
Custom Method with Type Inference
public static <K, V> Map<K, V> createMap(K key, V value) {
Map<K, V> map = new HashMap<>();
map.put(key, value);
return map;
}
// Usage
Map<Integer, String> map = createMap(1, "Mahesh"); // Compiler infers types
Code language: JavaScript (javascript)
Type inference makes your code shorter and easier to read. But remember — the compiler needs enough information to guess the types correctly.