A mechanism for performing ** type inference ** of ** local variables **, which has appeared since Java SE10. Infer the data type from the type on the right side. Type inference with var is done at compile time.
** * [What is a local variable] ** A variable declared in ** in a method ** (used as a formal argument or argument in a method)
** ・ Example of type inference by var **
var i = 10; //Infer that i is an int type from the value on the right side
** Only local variables can be type inferred by var! !! !! !! ** **
-For variables other than local variables (instance variables, static variables, ** method return type **) -If not initialized when the variable is declared (that is, if only "var i;" and the variable are created) ・ When initialized with null -For variables that assign array initialization
var infers the data type from the type on the right side. Then, the initializer ({}) used to create the array also infers the type of the array from the type of the value to be assigned. Since they infer each other, the type is not determined and a compile error occurs.
**-Example of array initialization that causes a compile error **
var array = {1,2,3};
However, if you declare the type when creating the value of the array on the right side, you can initialize the array with var.
** ・ Example of array initialization by var **
var array = new int []{1,2,3}; //You can create an int type array
As with arrays, you can also create an ArrayList with var.
**-Initialize ArrayList with var **
var list = new ArrayList<>();
The ** diamond operator ** of ArrayList returns ** Object type ** when there is no referenceable type. Therefore, the above code is the same as the code below.
var list = new ArrayList<Object>();
An Object type ArrayList is created as a list.
Recommended Posts