With Java 11
, for this code:
String[] arrayString = {"foo", "bar"};
SonarLint
say Declare this local variable with "var" instead.
So, I have tried:
var arrayString = {"foo", "bar"};
// or
var[] arrayString = {"foo", "bar"};
But now I get these errors:
Array initializer needs an explicit target-type
'var' is not allowed as an element type of an array
How can I declare correctly array variables or attributes.
var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.
In Java, var can be used only where type inference is desired; it cannot be used where a type is declared explicitly. If val were added, it too could be used only where type inference is used. The use of var or val in Java could not be used to control immutability if the type were declared explicitly.
The var keyword was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context. The below examples explain where var is used and also where you can't use it. 1. We can declare any datatype with the var keyword.
JEP 286 − Local Variable Type Inference Local Variable Type Inference is one of the most evident change to language available from Java 10 onwards. It allows to define a variable using var and without specifying the type of it. The compiler infers the type of the variable using the value provided.
You could use
var arrayString = new String[]{"foo", "bar"};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With