Search code examples
javavarsonarlint

SonarLint, Array of String: Declare this local variable with "var" instead = error


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.


Solution

  • You could use

    var arrayString = new String[]{"foo", "bar"};