Is there auto type inferring in Java?

Games Brainiac picture Games Brainiac · Apr 21, 2013 · Viewed 78.8k times · Source

Is there an auto variable type in Java like you have in C++?

An example:

for ( auto var : object_array)
    std::cout << var << std::endl;

for( auto var : object_array)
    var.do_something_that_only_this_particular_obj_can_do();

I know that there is an enhanced for loop in Java, but is there an auto? If not, is there a hack to doing this? I am referring to the new feature in C++11

Answer

sorrymissjackson picture sorrymissjackson · Oct 31, 2017

Might be Java 10 has what you (and I) want, through the var keyword.

var list = new ArrayList<String>();  // infers ArrayList<String>
var stream = list.stream();          // infers Stream<String>

From JDK Enhancement Proposals 286


Update: Yap, that feature made it into the Java 10 release!