50
var num = 1;
var city = "Taranto";
System.out.println(num);
System.out.println(city);
}
}
Now you should see the following output.
1
Taranto
How It Works
Prior to Java 10, you declared in the following way.
String city = "Taranto";
Next, you can declare the following.
var city = "Taranto"
It allows programmers to declare the type of the local variable instead of the actual
type and increases code readability. The compiler decides the type based on the value
assigned to the variable. In Java 11, the usage of var uniform
was extended to lambda
parameters, as explained in Chapter
6
.
The local variable type inference cannot be used as a global variable. In fact, if you
use the following, the IDE raises a compilation error.
//
instance variable
var x = 50;
public static void main(String[] args)
{
System.out.println(x);
}
The output is an error.
'var' is not allowed here
Chapter 2 enhanCements from Java 9 through Java 17
51
For more information on the var keyword,
see the documentation at
http://openjdk.java.net/jeps/286
.
Note the Jep–JDK enhancement proposal collects proposals for enhancements
to the JDK and allows openJDK to develop more informally changes. It does not
replace JCp, however, which is required to approve changes in Java apI.
Do'stlaringiz bilan baham: