Sage-Code Laboratory
index<--

Type Inference

All languages start to look like each other. In JDK 10 and later, you can declare local variables with non-null initializers using a special type named: "var" to define an identifier, which can help you write code that’s easier to read.

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.

Advantages

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.

Use cases

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;  

Restriction

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
>

Warning: Mixing multiple inference can cause a conflict and is not working correctly all the time. Therefore you should avoid these situations. Use "var" only when things are clear and do not abuse this feature.

Read next: Lambda Expressions