Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 246
Stéphane Millien Avatar asked May 10 '21 12:05

Stéphane Millien


People also ask

Why use var instead of type in Java?

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.

When should you use VAR in Java?

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.

What is var keyword in Java?

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.

What is the local variable type inference keyword since Java 10?

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.


Video Answer


1 Answers

You could use

var arrayString = new String[]{"foo", "bar"};
like image 102
Unmitigated Avatar answered Nov 14 '22 22:11

Unmitigated