"var" in Java!

"var" in Java!

What is var?

Long story short, var was introduced in Java 10 to reduce the boilerplate code. If you are a java developer who has worked on multiple projects (Java version < 10) you must be aware that how annoying it is to explicitly declare a variable that the declaration itself is occupying the whole line. Take a look at the below code :

import java.util.ArrayList; 

import java.util.HashMap; 

import java.util.List; import java.util.TreeMap;

public class Sample { 

    public static void main(String[] args) { 
        TreeMap<Integer, HashMap<Integer, Integer>> map = 
                                    new TreeMap<>();  
        List<List> graph = buildGraph(new int[][]{{},{}}); 
}

    private static List<List> buildGraph(int[][] matrix){ 
        List<List> graph = new ArrayList<>(); 
        // ... ..... ...... return graph; 
    }

}

This is where var comes into the picture. Now lets see the code where we are using var to remove a bunch of boilerplate code.

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.TreeMap;

public class Sample { 
    public static void main(String[] args) { 
            var map = new 
                TreeMap<Integer, HashMap<Integer, Integer>>(); 
            var graph = buildGraph(new int[][]{{}, {}}); 
    }

    private static List<List> buildGraph(int[][] matrix) { 
            List<List>     graph = new ArrayList<>(); 
            // ... ..... ...... return graph; 
    }

}
  • If you take a look at the main method we can observe that we no more need to declare the variable type explicitly. The above example might be small but if you are working on a project that has thousands of lines, imagine how helpful var would be.

  • var is not a keyword, you can use it as a variable name.

     float var = 3.14f;✅
    
  • If you declare a var, you must initialize it.

    var myAge; ❌ 
    var userAge = 18; ✅
    
  • var is only used for storing variables, it cannot be used to store lambdas!

  • var cannot be used for generics!!

    var<Integer> list = new ArrayList<Integer>(); ❌
    
  • var can be only used for local declaration, not a global declaration.

    public class Sample { 
    
        var globalAge = 23; ❌
        public static void main(String[] args) { 
            var localAge = 18; ✅ 
        }
    }
    

    Official Documentation

Hope you liked this blog!

Did you find this article valuable?

Support Bharath Kalyan S by becoming a sponsor. Any amount is appreciated!