Type inference is a compiler feature that identify the required type using a logic deduction. When you declare with "var" you do not have to specify the data type explicit. THe compiler will assign a data type that is default for a particular data literal or expression used to initialize a variable identifier in question.
Local variable declarations can be simpler and more readable by using var type, that eliminate redundant information. However, it can also make code less readable by omitting useful information. Consequently, use this feature with judgment; no strict rule exists about when it should and shouldn't be used.
You can use var for local variables. You can use var in loops, selections and lambda expressions. It can be used to define a list of parameters and local constants.
var list = new ArrayList<String>(); // infers ArrayList<String>
var stream = list.stream(); // infers Stream<String>
var path = Paths.get(fileName); // infers Path
var bytes = Files.readAllBytes(path); // infers bytes[]
final var PI2 = 3.14159265; // infers Float
List<String> myList = Arrays.asList("a", "b", "c");
for (var element : myList) {...} // infers String
for (var counter = 0; counter < 10; counter++) {...} // infers int
try (var input =
new FileInputStream("validation.txt")) {...} // infers FileInputStream
(var a, var b) -> a + b;
However there are basicly no global variables in Java. Nothing exists outside of class in Java, however you can't use var with static final variables, so you can't use "var" everywhere.
import static java.lang.System.out;
class Main {
public static void main(String[] args) {
out.format("x=%d%n",Global.x);
out.println("done.");
}
}
class Global {
public static final var x = 12;
}
sh -c javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')
./Main.java:11: error: 'var' is not allowed here
public static final var x = 12;
^
1 error
exit status 1
>
Read next: Lambda Expressions