In java, the type is always used in the declaration of a variable.
That’s up to Java 9. In Java 10, you can declare with var
. And Ambdas parameters have never needed 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 something 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 the type String
. To illustrate with a more extreme case:
Map<String, List<FuncionarioEmpresaDTO>> x = criaUmMapDosFuncionários();
umOutroMétodoQueRecebeOMapDosFuncionários(x);
maisOutroMétodoQueRecebeOMapDosFuncionários(x);
It gets simpler 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 most obscure code.
Finally, each case is a case. The use of var
can make the code thinner or more obscure. Like any other resource, it is something that should be used with common sense.
"In java, the type is always used in the declaration of a variable." - That’s up to Java 9. In Java 10, you can declare with
var
. And Ambdas parameters have never needed explicit type declaration (except in a few cases) since they were introduced in Java 8.– Victor Stafusa
I understand, I’m off this new update... but what about the question?
– Long Johnson
I suggest reading: What is the difference between a static and dynamic programming language?
– rbz