Type Inference in Java

Profile picture for user arilio666

In Java, type inference is a feature introduced in Java 7 that allows the compiler to automatically deduce the data type of a variable based on its value or the context in which it is used. Type inference eliminates the need to specify a variable's data type in certain situations, making the code more concise.

  • The diamond operator (<>) is used for type inference when creating instances of generic classes. 
  • Instead of explicitly specifying the type arguments when creating an object of a generic class, the diamond operator allows the compiler to infer the type arguments based on the type of object being assigned to the variable.
// Without type inference
List<String> list = new ArrayList<String>();
// With type inference using the diamond operator
List<String> list = new ArrayList<>();


Old Approach:

public class Calculator {
    public static void showAllInfoList(List<Integer> list) {
        if (!list.isEmpty()) {
            list.forEach(System.out::println);
        } else
            System.out.println("Empty List!!");
    }
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<Integer>();
        list1.add(11);
        showAllInfoList(list1);
    }
}
  • Here is the old approach to creating a list without mentioning type explicitly on both sides.

New Approach:

package week1.day2;
import java.util.ArrayList;
import java.util.List;
public class Calculator {
    public static void showAllInfoList(List<Integer> list) {
        if (!list.isEmpty()) {
            list.forEach(System.out::println);
        } else
            System.out.println("Empty List!!");
    }
    public static void main(String[] args) {
        List<Integer> list2 = new ArrayList<>(); // You can left it blank, compiler can infer type
        list2.add(12);
        showAllInfoList(list2);
    }
}
  • Using the diamond operator now, we can leave it blank now that the compiler can infer the type automatically.
Tags