Languages
[Edit]
EN

Java 10 - var type / keyword with code examples

5 points
Created by:
Marcin
15680

In this post we have collection of code examples of var type introduced in java 10.

1. Var with List and Stream

// before java 10
List<Integer> nums = new ArrayList<>();
Stream<Integer> stream = nums.stream();

// with java 10 var
var nums = new ArrayList<Integer>();   // infers ArrayList
var stream = nums.stream();            // infers Stream

2. Var basic usage case

// before java 10
BigInteger bigInt1 = new BigInteger("123");

// with java 10 var
var bigInt2 = new BigInteger("123");

// other examples:
Integer integer1 = 123;
var integer2 = 123;

String str1 = "123";
var str2 = "123";

3. Assign new value to var

// assign new value to var
var bigInt = new BigInteger("123");
bigInt = new BigInteger("456"); // it's ok

4. Can't initialize var with null

// var bigInt = null;

// You can't initialize var with null
// Error: java: cannot infer type for local variable bigInt
// (variable initializer is 'null')

5. Var with if

var no = 5; // infers int
if (no > 4) {
    System.out.println(no); // 5
}

6. Var with loops

6.1 var with for loop

var numbers = List.of(1, 2, 3, 4);
for (var i = 0; i < numbers.size(); i++) {
    System.out.print(numbers.get(i) + " "); // 1 2 3 4
}

6.2 var with for each loop

var numbers = List.of(1, 2, 3, 4);
for (var no : numbers) {
    System.out.print(no + " "); // 1 2 3 4
}

7. Var keyword with stream example

var numbers = List.of(1, 2, 3, 4);
var res = numbers.stream()
        .filter(no -> no > 2)
        .collect(Collectors.toList());
System.out.println(res); // [3, 4]
System.out.println(res.getClass()); // class java.util.ArrayList

8. Var with HashMap and iteration

// before java 10
Map<String, List<Integer>> userToOrdersId = new HashMap<>();
for (Map.Entry<String, List<Integer>> entry : userToOrdersId.entrySet()) {
    List<Integer> orders = entry.getValue();
}

// with java 10 var
var userToOrdersId = new HashMap<String, List<Integer>>();
for (var entry : userToOrdersId.entrySet()) {
    var orders = entry.getValue();
}

9. Var with diamond operator <>

// If we use var with diamond operator <>:
// var list = new ArrayList<>();
// it is the same to as:
// var list = new ArrayList<Object>();
// or
// ArrayList<Object> list2 = new ArrayList<>();

var list = new ArrayList<>();
list.add(123);
list.add("123");
list.add(new BigInteger("1234"));

// Error: java: incompatible types: 
// java.lang.Object cannot be converted to int
// int idx0Int = list.get(0);

// will work, but... :
Object idx0 = list.get(0);
int idx0Cast = (int) list.get(0);

System.out.println(list.toString()); // [123, 123, 1234]
System.out.println(list.getClass()); // class java.util.ArrayList

10. Var with diamond operator <> explicit type

var list = new ArrayList<Integer>();
list.add(123);
// Error: java: incompatible types: 
// java.lang.String cannot be converted to java.lang.Integer
// list.add("123");

11. Var + try with resources 

InputStreamReader + BufferedReader - long declaration

// before java 10
URL url = new URL("https://mvnrepository.com/");
try (InputStreamReader in = new InputStreamReader(url.openStream());
     BufferedReader br = new BufferedReader(in)) {
    String line = br.readLine();
    // ..
}

// with java 10 var
var url = new URL("https://mvnrepository.com/");
try (var in = new InputStreamReader(url.openStream());
     var br = new BufferedReader(in)) {
    String line = br.readLine();
    // ..
}

12. Var + method call - long class names

// before java 10
Map<QualifierAnnotationAutowireCandidateResolver,
        CustomAutowireConfigurer> cfgMap1 = createCfgMap();

// with java 10 var
var cfgMap2 = createCfgMap();

// method to create cfgMap
private Map<QualifierAnnotationAutowireCandidateResolver, 
        CustomAutowireConfigurer> createCfgMap() {
    Map<QualifierAnnotationAutowireCandidateResolver, 
            CustomAutowireConfigurer> cfgMap = new HashMap<>();
    // ..
    return cfgMap;
}

13. Var incorrect usage

Can't declarate and init in separated lines:

// won't compile
// java: cannot infer type for local variable bigInt1
// (cannot use 'var' on variable without initializer)
// var bigInt1;
// bigInt1 = new BigInteger("123");

// fixed:
var bigInt2 = new BigInteger("123");

14. Var incorrect usage - array initialization

// won't compile
// Error: java: cannot infer type for local variable nums
// (array initializer needs an explicit target-type)
// var nums = {1, 2, 3};

// fixed:
int[] nums = {1, 2, 3};

15. Var with lambda - incorrect usage

Can't initialize var with lambda expressions

// You can't initialize var with lambda expressions
// won't work
// Error: java: cannot infer type for local variable runnable1
// (lambda expression needs an explicit target-type)
// var runnable1 = () -> {};

// fixed:
Runnable runnable2 = () -> {};

16. Why to use java 10 var keyword?

  • Java 10 var is designed to improve the readability of code

Link to Brian Goetz post - JEP 286: Local-Variable Type Inference

17. What is type inference?

Type inference refers to the automatic detection of the data type of an expression in a programming language.

Type inference - wikipedia

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join