In java, the type is always used in the declaration of a variable.
This is up to Java 9. In Java 10, you can declare with var
. And lambda parameters have never needed an explicit type declaration (except in a few cases) since they were introduced in Java 8.
Knowing which is more readable depends a lot and is subjective. It depends on what you want to do with the code. For example:
String x = "abc";
String z = "def";
System.out.println(x + z);
Or:
var x = "abc";
var z = "def";
System.out.println(x + z);
The second is more readable because it is obvious from the context that the variable is of type String
. To illustrate with a more extreme case:
Map<String, List<FuncionarioEmpresaDTO>> x = criaUmMapDosFuncionários();
umOutroMétodoQueRecebeOMapDosFuncionários(x);
maisOutroMétodoQueRecebeOMapDosFuncionários(x);
Make it simple with this:
var x = criaUmMapDosFuncionários();
umOutroMétodoQueRecebeOMapDosFuncionários(x);
maisOutroMétodoQueRecebeOMapDosFuncionários(x);
However, this is not always true:
var x = métodoMuitoLoucoQueRetornaTudoOqueVocêImagina();
var y = x.métodoQueVocêNemSabiaQueExistia();
System.out.println(y);
In this case, the use of var
left the code more obscure.
Anyway, every case is a case. Using var
may make the code leaner or darker. Like any other feature, it is something that should be used with good judgment.