Programs written in the Java language often have a significant amount of excess and repeated syntax. A class
name may be repeated many times, for example.
With var
, a keyword, we can minimize this—we can use var
to refer to the class
name of a variable. The Java compiler infers the class
name on its own. No runtime cost is incurred.
This Java program uses the "var
" keyword in many different ways. At the bottom of the program, we have a couple extra types—another class
and a record.
ExampleClass
instance, and instead of specifying "ExampleClass
" as the type, we use the var
-keyword.ExampleRecord
) and refer to as a var
. The var
keyword is a different syntax for the same type.var
for other types like int
, but this may be less useful as no code source size reduction is achieved.var
-keyword can be used as the argument type to a lambda expression. The compiler infers that the type here should be int
.var
keyword in for
-loop enumerations often leads to easier-to-read, clearer code.import java.util.function.*; public class Program { public static void main(String[] args) { // Part 1: create class instance and refer to it with var. var c = new ExampleClass(); c.value = 10; System.out.println(c.value); // Part 2: create record and refer to it with var. var r = new ExampleRecord(10); System.out.println(r); // Part 3: use var for an int, and compare to another int. var number = 10; int number2 = 10; if (number == number2) { System.out.println("2 ints are the same"); } // Part 4: use var as a lambda expression argument. Function<Integer, Integer> lambda = (var x) -> (x + 50); int result = lambda.apply(10); System.out.println(result); // Part 5: use var in a for-loop. var names = new String[] { "cat", "frog", "bird" }; for (var name : names) { System.out.println(name); } } } // For the class and record examples. class ExampleClass { public int value; } record ExampleRecord(int value) {}10 ExampleRecord[value=10] 2 ints are the same 60 cat frog bird
When we need to repeat a long type name for some reason, replacing those uses with "var
" probably improves code quality.
short
types like int
, or a type only used once, using var
would not be as beneficial to the code.var
keyword, not just use it everywhere possible.The var
-keyword can make some difficult-to-read and cumbersome code much more elegant to review. It tells the compiler to figure out (and use) the type on its own.