Type inference means that the compiler can determine the exact type you want to use from the context you're using it in.
One example is using methods that have generic type parameters. A generic type parameter is much like a regular method parameter, but instead of assigning a value to it, you assign a type to it. You even have to pass types to a generic method!
This method will return a
List<String>. However, the compiler can
infer that you want a
List<String> if you assign the return value to a variable of that type. Then you don't have to pass the type argument explicitly:
Since Java 7, there's a second situation in which the compiler uses type inference. Before Java 7, when you assigned a new generic object to a variable, or returned it from a method, you explicitly had to state the type argument of the object:
You can see that you have to repeat the type argument when constructing the object, even though it should be clear from the context. With Java 7, you can use the
diamond operator instead:
Here the compiler will also infer what the type argument needs to be.